Search code examples
c#ajaxasp.net-corehttpclient

HTTP status code 500, .net core CORS And HttpClient errors


I've got some problems concerning CORS/HttpClient in dotnet core. First of all my Application is structured like this:

Webapp -> Microservice-Gateway -> multiple Microservices

If I do an Ajax call from my Webapp

$.ajax({
        url: "https://[actual gateway Url]/customer/" + customerId,
        type: "GET",
        timeout: 60000,
        crossDomain: true,
        dataType: "json",
        success: data => {
            //...
        }
    });

to the Gateway-Server I receive sometimes following error Message:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50595' is therefore not allowed access. The response had HTTP status code 500.

Internally however my gateway throws this error if I debug:

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: The operation timed out

I tried to solve the first error by adding following code in the gateway and every microservice:

public void ConfigureServices(IServiceCollection services) {
        var corsBuilder = new CorsPolicyBuilder();
        corsBuilder.AllowAnyHeader();
        corsBuilder.AllowAnyMethod();
        corsBuilder.AllowAnyOrigin();
        corsBuilder.AllowCredentials();

        services.AddCors(options => {
            options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
        });
 //..
 }
 public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
        app.UseCors("SiteCorsPolicy");
 //..
 }

And just to be sure I also added

[EnableCors("SiteCorsPolicy")]

to every controller. The second problem I tried to solve by creating an HttpClient as Singleton in my Gateway and modifying following properties:

var client = new HttpClient();
client.Timeout = new TimeSpan(0, 10, 0);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
services.AddSingleton(client);

My gateway sends HTTP-requests like that:

[HttpGet("{id}")]
public async Task<JsonResult> GetById(int id) {
    var response = await _client.GetAsync(new Uri(ServiceUrls.Customer + $"{id}"));

    if (!response.IsSuccessStatusCode)
        return new JsonResult(BadRequest($"{(int)response.StatusCode}: {response.ReasonPhrase}"));

    var customer = JsonConvert.DeserializeObject<CustomerViewModel>(await response.Content.ReadAsStringAsync());
    return new JsonResult(customer);
}

As I said, sometimes it works and sometimes it doesn't. Maybe you could give me some ideas whats my mistake. Thanks in advance!

Edit: The problem seems to appear more often if there are multiple async ajax calls from the Webapp at once. But this could also be just a feeling.


Solution

  • Ok guys,

    thanks for getting me into the right direction. I think I found a workaround/fix. I had to set following property in my gateway:

    ServicePointManager.DefaultConnectionLimit = int.MaxValue;