【问题标题】:How to allow CORS in ASP.NET WebAPI如何在 ASP.NET WebAPI 中允许 CORS
【发布时间】:2021-10-23 23:49:48
【问题描述】:

我正在尝试从我的 Web 应用程序向我的 ASP.NET 端点(本地所有内容)执行 ajax 发布请求,以在我的数据库中插入数据,但我总是收到 POST http://localhost:44326/radar/insertConfig net::ERR_CONNECTION_RESET

到目前为止我已经收集到的信息:通过 Insomnia 调用端点时,该端点可以完美运行; 我有其他 GET 请求在相同条件下完美运行(相同页面、相同域等); 我已经测试了对公共端点的 POST 请求,一切正常;请求永远不会离开浏览器(或永远不会到达目的地)。 仅当从我的 Web 应用程序向我的 API 发送 POST 请求时才会出现此问题。

我尝试过:使用其他浏览器(Chrome、Edge、Firefox)、删除 cookie、清除缓存、重置我的连接、重置我的计算机、尝试从不同的连接。

注意 1:我正在使用我无法关闭的 VPN 和防病毒软件(两者都无法关闭)。

注意2:通过firefox完成时,错误变为:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:44326/radar/insertConfig. (Reason: CORS request did not succeed).

我的要求:

var json = JSON.stringify(obj);
var url = "http://localhost:44326/radar/insertConfig";
$.post(url, json, function (status) {
    if (status == "success")
        alert("yay");
    else
        alert("nay");
}, "json");

发生错误的行:plugins.bundle.js:9838

xhr.send( options.hasContent && options.data || null );

可能是什么问题?

更新:我在我的服务器中添加了一个中间件,如下所示:

app.Use(async (context, next) =>
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            await next.Invoke();
        });

但如果我这样做,则返回 415(不支持的媒体类型)。我试图通过更改我的请求来解决这个问题:

$.ajax({
    url: url,
    type: 'post',
    data: json,
    contentType: 'application/json',
    dataType: 'json',
    success: function (status) {
        if (status == "success")
            alert("yay");
        else
            alert("nay");
    }
});

但话又说回来,CORS 错误返回...

【问题讨论】:

  • 尝试使用相对路径...(如果您必须使用绝对路径,请尝试使用 https 和/或 127.0.0.1)
  • 您需要更新服务的(ASP.NET 端点)CORS 配置以接受来自本地主机域的请求。我认为出于测试目的,您可以将Access-Control-Allow-Origin: * 设置为接受对任何来源的请求,但我建议之后正确设置它。这是参考:developer.mozilla.org/en-US/docs/Web/HTTP/CORS
  • @pcalkins 不起作用,但使用 https 使此错误返回而不是 Access to XMLHttpRequest at 'https://localhost:44326/radar/insertConfig' from origin 'https://localhost:44301' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • @nmina 这种工作,我为此添加了一个中间件,但后来发生了这个错误:net::ERR_HTTP2_PROTOCOL_ERROR

标签: javascript asp.net ajax post


【解决方案1】:

从错误消息看来,您的客户端和服务器来自不同的域,为了能够从不同的域调用您的服务器,您需要在服务器上启用 CORS。

对于 asp.net 服务器,您可以使用 Microsoft.AspNet.WebApi.Cors nuget 包并在控制器上添加 EnableCors 属性,如下所示 [EnableCors(origins: "http://{your-client-domain}", headers: "*", methods: "*")]

【讨论】:

  • 这种工作,我在响应头中添加了一个允许 cors 的中间件,但后来发生了这个错误:net::ERR_HTTP2_PROTOCOL_ERROR
  • 标题名称中多了一个,
  • 打错字了,谢谢。但是,错误仍然存​​在......
  • 您在管道订单中究竟在哪里添加了中间件?当您从同一域中的浏览器查询您的服务器时,您还可以在响应标头中看到标头Access-Control-Allow-Origin 吗?
【解决方案2】:

我必须改变一些东西才能让它工作,这是我的解决方案:

第 1 步:将其添加到 ConfigureServices 和 Configure(默认情况下它们在 Startup.cs 中)

public void ConfigureServices(IServiceCollection services)
{
        services.AddCors(options =>
        {
            options.AddPolicy(name: "MyPolicy",
                builder =>
                {
                    //This is how you tell your app to allow cors
                    builder.WithOrigins("*")
                            .WithMethods("POST", "DELETE", "GET")
                            .AllowAnyHeader();
                });
        });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCors("MyPolicy");
}

第 2 步:将请求更改为 $.ajax 而不是 $.post

$.ajax({
    url: url,
    type: "post",
    crossDomain: true,
    data: json,
    contentType: "application/json",
    dataType: "json"
});

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 1970-01-01
    • 2014-12-20
    • 2016-06-08
    • 2021-12-31
    • 2018-03-02
    • 2019-12-30
    • 2021-12-30
    相关资源
    最近更新 更多