web api中的交叉起源错误2 c# - 原因:缺少CORS标题“Access-Control-Allow-Origin”

时间:2016-04-30 12:30:17

标签: c# api asp.net-web-api cross-domain asp.net-web-api2

我已经尝试过所有方法来解决这个跨源问题。但我无法弄清楚这个问题是什么。

我添加了这是我的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.NET\Framework\v4.0.30319\aspnet_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.NET\Framework64\v4.0.30319\aspnet_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();
        }
    }

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

请帮助我们!

2 个答案:

答案 0 :(得分:1)

您只需在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>

答案 1 :(得分:0)

假设您有一个名为int hijriYear = umalqura.getYear(); System.out.println("Year (hirji-umalqura): " + hijriYear); // 1437 的控制器,那么您必须在TestController中启用cors,如下所示

Get method

其他方法也是这样的。

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