Web API 2 中的跨源错误 原因:缺少 CORS 标头'Access-Control-Allow-Origin'



我已经尝试了所有方法来解决这个跨原点问题。但我搞不清楚问题出在哪里。

我添加了这是我的webapiconfig.cs

 var cors = new EnableCorsAttribute("*", "*", "*");
 config.EnableCors(cors);
 config.MapHttpAttributeRoutes();

和在webconfig 中

<handlers>
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFramework64v4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

Global.asax

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);   
    }
    protected void Application_BeginRequest()
    {
        if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
        {
            Response.Flush();
        }
    }

我添加了金块包Install-Package Microsoft.AspNet.WebApi.Cors

伙计们,请帮帮我!

您只需要在web API的web.config文件中添加以下代码:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
     <add name="Access-Control-Allow-Credentials" value="true" />
    </customHeaders>
  </httpProtocol>

假设您有一个名为TestController的控制器,那么您必须在Get method中启用cors,如下所示

public class TestController : ApiController
    {
            [EnableCors(origins: "*", headers: "*", methods: "*")]
            public string Get()
            {
                return "Hello world";
            }
   }

其他方法也类似于此。

有用的链接https://msdn.microsoft.com/en-us/magazine/dn532203.aspx?f=255&MSPP错误=-2147217396

相关内容

  • 没有找到相关文章

最新更新