HTTP状态码500,.net核心CORS和HttpClient错误 [英] HTTP status code 500, .net core CORS And HttpClient errors

查看:547
本文介绍了HTTP状态码500,.net核心CORS和HttpClient错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在dotnet核心中遇到了有关CORS/HttpClient的问题.首先,我的应用程序的结构如下:

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

如果我通过Webapp进行Ajax呼叫

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:

请求的请求上没有'Access-Control-Allow-Origin'标头 资源.因此,不允许来源' http://localhost:50595 ' 使用权.响应的HTTP状态码为500.

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:发送时发生错误 请求. ---> System.Net.Http.WinHttpException:该操作 超时

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");
 //..
 }

为了确保我也添加了

[EnableCors("SiteCorsPolicy")]

给每个控制器. 我试图通过在网关中将HttpClient创建为Singleton并修改以下属性来解决的第二个问题:

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);

我的网关发送这样的HTTP请求:

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!

如果同时有多个来自Webapp的异步ajax调用,则该问题似乎更经常出现.但这也可能只是一种感觉.

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.

推荐答案

好的,

感谢您指引我正确的方向.我想我找到了一种解决方法/修复.我必须在网关中设置以下属性:

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;

这篇关于HTTP状态码500,.net核心CORS和HttpClient错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆