Я написал общую службу клиентов: < /p>
Код: Выделить всё
public class HttpClientHelper
{
private readonly IHttpClientFactory _httpClientFactory;
public HttpClientHelper(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task MakeHttpRequestAsync(
string clientName,
string url,
HttpMethod httpMethod,
TRequest requestBody = default,
bool handleErrors = false)
{
// Get a named HttpClient instance
var client = _httpClientFactory.CreateClient(clientName);
var request = new HttpRequestMessage
{
Method = httpMethod,
RequestUri = new Uri(url)
};
// Serialize the request body to JSON (if it exists)
if (requestBody != null)
{
var json = JsonSerializer.Serialize(requestBody);
request.Content = new StringContent(json,
Encoding.UTF8, "application/json");
}
// Send the HTTP request
var response = await client.SendAsync(request);
// Handle errors if specified
if (handleErrors && !response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Failed: {response.StatusCode}");
}
// Deserialize the response JSON into the specified type
var responseJson = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize(responseJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
}
< /code>
Теперь я хочу получить более структурированный возврат из этой функции. Например, мне нравится использовать для всех ответов что -то вроде < /p>
public class ApiResponse where T : class
{
public T? Data { get; set; }
public string? ErrorMessage { get; set; }
public int HttpErrorCode { get; set; } = 200;
public bool Success { get; set; } = false;
}
< /code>
Мне не нужно обрабатывать ошибки в основном коде, и все хорошо управляется в общем клиенте API. Если в вызове есть ошибка, в Apiresponse
Если я напишу этот код:
Код: Выделить всё
public async Task
MakeHttpRequestAsync(
...
)
{
// code
}
type или имя пространства имен tresponse не может быть найдено (вам не хватает директив или ссылки на сборку?) код.
Есть ли способ реализовать это?
Подробнее здесь: https://stackoverflow.com/questions/795 ... on-returns