Возникла проблема при отправке POST запроса к API через HttpClient. Есть код:
private Task<TOut> PostAsync<TIn, TOut>(Uri baseUri, string requestUri, TIn input, string token = null)
{
return HttpRequestAsync<TOut>(c => c.PostAsJsonAsync(new Uri(baseUri, requestUri), input), token);
}
private Task<TOut> HttpRequestAsync<TOut>(Func<HttpClient, Task<HttpResponseMessage>> httpRequest, string token = null)
{
return HttpRequestAsync(httpRequest, r => r.Content.ReadAsAsync<TOut>(), token);
}
private async Task<TOut> HttpRequestAsync<TOut>(Func<HttpClient, Task<HttpResponseMessage>> httpRequest, Func<HttpResponseMessage, Task<TOut>> httpResponse, string token = null)
{
using (var client = CreateHttpClient(token))
{
try
{
var response = await httpRequest(client);
using (response)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new NotAuthorizedException();
}
if (response.StatusCode == HttpStatusCode.NotFound)
{
throw new NotFoundException
{
AnswerStatusCode = response.StatusCode,
AnswerReasonPhrase = response.ReasonPhrase
};
}
if (response.StatusCode != HttpStatusCode.NotFound &&
response.StatusCode != HttpStatusCode.OK)
{
throw new InvalidOperationException("Ошибка сервера сервиса маркировки");
}
var result = await httpResponse(response);
return result;
}
}
catch (NotAuthorizedException)
{
throw;
}
catch (NotFoundException)
{
throw;
}
catch (InvalidOperationException)
{
throw;
}
catch (Exception e)
{
throw new InvalidOperationException("Ошибка запроса к системе", e);
}
}
}
private HttpClient CreateHttpClient()
{
return new HttpClient();
}
private HttpClient CreateHttpClient(string token)
{
var client = CreateHttpClient();
if (!string.IsNullOrEmpty(token))
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return client;
}
private HttpClient CreateHttpClient(Dictionary<string, string> headers)
{
var client = CreateHttpClient();
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
return client;
}
public async Task<long> SendRegistrationRequest(IsmpBaseRequestModel<RegistrationRequest> request, string token)
{
try
{
var uri = new Uri(@"https://int01.gismt.crpt.tech/api/v3/true-api");
var method = "elk/registration";
var res = await PostAsync<IsmpBaseRequestModel<RegistrationRequest>, RegistrationResponse>(uri, method, request, token);
return res.RequestId;
}
catch (NotAuthorizedException ex)
{
throw new Exception("Ошибка авторизации в ГИС МТ", ex);
}
catch (NotFoundException ex)
{
throw new Exception("Ресурс не найден", ex);
}
catch (Exception ex)
{
throw new Exception("Ошибка отправки запроса на регистрацию в ГИС МТ", ex);
}
}
В ответ сервер присылает 401 статус и ошибку "Cannot convert access token to JSON". JWT токен формируется правильно, потому что при отправке запроса из Fiddler или Postman всё хорошо, статус 200 + ожидаемый ответ.
Пробовал прикреплять сертификат к HttpClient, ничего не выходит. Еще заметил, что в Fiddler не отображается заголовок Authorization Bearer {access_token}, в то время как в запросе из Postman этот заголовок есть.
Подскажите, пожалуйста, в чем может быть проблема?