这个错误是由于 CORS (跨域资源共享)策略导致的,通常是由于服务器没有正确配置 CORS 响应头所导致的。您可以尝试在服务器端添加以下代码来解决该问题:

  1. 在 WebApi 项目的 Web.config 文件中添加以下代码:
<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name='Access-Control-Allow-Origin' value='*' />
            <add name='Access-Control-Allow-Methods' value='GET, POST, PUT, DELETE, OPTIONS' />
            <add name='Access-Control-Allow-Headers' value='Content-Type, Authorization, X-Requested-With' />
        </customHeaders>
    </httpProtocol>
</system.webServer>
  1. 在 WebApi 项目的 Global.asax.cs 文件中添加以下代码:
protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader('Access-Control-Allow-Origin', '*');

    if (HttpContext.Current.Request.HttpMethod == 'OPTIONS')
    {
        HttpContext.Current.Response.AddHeader('Access-Control-Allow-Methods', 'POST, PUT, DELETE');

        HttpContext.Current.Response.AddHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
        HttpContext.Current.Response.AddHeader('Access-Control-Max-Age', '1728000');
        HttpContext.Current.Response.End();
    }
}

以上代码将允许来自任何来源的跨域请求,并允许 GET、POST、PUT、DELETE 和 OPTIONS 方法。您可以根据需要进行修改。

另外,您还需要确保客户端使用的是支持 CORS 的浏览器,并且使用的是最新版本的 WebApi。

C# WebAPI .NET 4.5.1 跨域请求报错 'null' 阻止访问: 解决 CORS 策略问题

原文地址: https://www.cveoy.top/t/topic/mwOl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录