ASP.NET Core — код состояния ответа не указывает на успех: 500 (внутренняя ошибка сервера) в HttpResponseMessage.EnsureSC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Гость
 ASP.NET Core — код состояния ответа не указывает на успех: 500 (внутренняя ошибка сервера) в HttpResponseMessage.EnsureS

Сообщение Гость »


В веб-API ASP.NET Core я использую API С SOAP XML.
Я ожидал отправить запрос к API и получить ответ
Поначалу все работало, но вдруг появилась такая ошибка:

Код: Выделить всё

"System.Net.Http.HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).\r\n   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()\r\n   at RequestHandler.SendSoapWebRequest(String url, String action, String xmlString) in C:\\WebRequestHandlers\\RequestHandler.cs:line 64\r\n   at Implementations.ChequeBooksServices.GetQueryChequeBookAsync(QueryChequeBookRequestDto chequeBookDto) in C:\\ChequeBooksServices.cs:line 135",
Оно подчеркивает:

Код: Выделить всё

using (var response = await _httpClient.SendAsync(request))
а также:

Код: Выделить всё

var response = await _requestHandler.SendSoapWebRequest(chequeUrl, action, xmlMessage);
ОСНОВНОЙ КОД:
program.cs:

Код: Выделить всё

var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
var environment = builder.Environment;
// Add services to the container.
builder.Services.AddHttpClient("Checkbook")
.ConfigurePrimaryHttpMessageHandler(() =>
{
// Allowing Untrusted SSL Certificates
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
//handler.SslProtocols.
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) => true;
return handler;
});
appsettings.json:

Код: Выделить всё

  "ChequeBooksEndpoints": {
"chequeBookBaseUrl": "https://myapi.com:1232/SchooAppService/SchoolAppService",
}
RequestHandler:

Код: Выделить всё

public class RequestHandler : IRequestHandler
{
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
private readonly IHttpClientFactory _httpClientFactory;
private readonly AsyncRetryPolicy _retryPolicy;
public RequestHandler(
ILogger logger,
HttpClient httpClient,
IHttpClientFactory httpClientFactory
)
{
_logger = logger;
this._httpClient = httpClientFactory.CreateClient("Checkbook");

// Apply the HttpClientHandler to the HttpClient
_httpClient.Timeout = TimeSpan.FromMinutes(5); // Set timeout to 5 minutes
_httpClient.DefaultRequestHeaders.ConnectionClose = true; // Disable connection close after each request
_httpClient.DefaultRequestHeaders.Accept.Clear(); // Clear default Accept header
_httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml")); // Set Accept header
}
public async Task SendSoapWebRequest(string url, string action, string xmlString)
{
try
{
// Set headers and content
var request = new HttpRequestMessage(HttpMethod.Post, url) { Version = new Version(2, 0) };
request.Headers.Add("SOAPAction", action);
request.Content = new StringContent(xmlString, Encoding.UTF8, "text/xml");

// Send the request and get the response
using (var response = await _httpClient.SendAsync(request))
{
// Ensure the request was successful before reading the content
response.EnsureSuccessStatusCode();

// Read the content of the response
return await response.Content.ReadAsStringAsync();
}
}
catch (HttpRequestException httpEx)
{
_logger.LogError($"HttpRequestException while sending SOAP request to {url}. Error: {httpEx}");
throw;
}
catch (OperationCanceledException cancelEx) when (cancelEx.CancellationToken.IsCancellationRequested)
{
_logger.LogError($"The SOAP request to {url} timed out. Error: {cancelEx}");
throw;
}
catch (OperationCanceledException cancelEx)
{
_logger.LogError($"The SOAP request to {url} was canceled.  Error: {cancelEx}");
throw new TimeoutException("The SOAP request timed out.", cancelEx);
}
catch (Exception exc)
{
_logger.LogError($"An error occurred while sending SOAP request to {url}. Error: {exc}");
throw new InvalidOperationException("Unable to post soap object.", exc);
}
}
}
GetQueryChequeBookAsync:

Код: Выделить всё

   public async Task GetQueryChequeBookAsync(QueryChequeBookRequestDto chequeBookDto)
{
Response checkBookResponse = new Response();
try
{
string chequeUrl = chequeBookBaseUrl;

string xmlMessage = await _chequeBooksProcessors.ComposeQueryChequeBookRequest(chequeBookDto);
string action = "";
var response = await _requestHandler.SendSoapWebRequest(chequeUrl, action, xmlMessage);

if (response != null)
{
var finalResponse = await XmlToObjectssSerializer.TransposeXmlResponseToObject(response);
if (finalResponse.Body.QUERYCHECKBOOKIOFSRES.FCUBSHEADER.MSGSTAT == "SUCCESS")
{
checkBookResponse.Data = finalResponse;
checkBookResponse.Successful = true;
}
else
{
checkBookResponse.Data = finalResponse;
checkBookResponse.Successful = false;
}
}
else
{
// Handle unsuccessful response from the SOAP request
checkBookResponse.Successful = false;
_logger.LogError("Failed to process SOAP request");
}

return checkBookResponse;
}
catch (Exception ex)
{
checkBookResponse.Successful = false;
_logger.LogError("An error occurred while processing the request: " + ex.ToString());
return checkBookResponse;
}
}


Источник: https://stackoverflow.com/questions/781 ... ternal-ser
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»