两个不同服务器上的Angular2和WebAPI应用程序之间的CORS问题

时间:2017-07-06 14:18:20

标签: cors asp.net-web-api2

当我的Angular2应用程序在我自己的计算机上运行但WebAPI应用程序在Web服务器上的IIS上运行时,我遇到了Angular2应用程序和WebAPI应用程序之间CORS的问题。有趣的是,如果我在自己的机器上运行这两个应用程序,一切正常。

我在Chrome中收到以下错误: -

XMLHttpRequest无法加载http://fowebtst01l:81/FilePusher.Service/api/version。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:4200”访问。响应的HTTP状态代码为401。

我在我的WebAPI应用程序中安装了CORS nuget包,并使用

在我的WebApiConfig类中启用它
            var attrib = new EnableCorsAttribute("*", "*", "*") {SupportsCredentials = true};
        config.EnableCors(attrib);

我还将此代码添加到我的Global.asax.cs文件中: -

        protected void Application_BeginRequest()
    {
        if (Request.HttpMethod == "OPTIONS")
        {
            string header = Request.Headers.GetValues("Origin")[0];

            Response.StatusCode = (int)HttpStatusCode.OK;
            Response.AppendHeader("Access-Control-Allow-Origin", header);
            Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            Response.AppendHeader("Access-Control-Allow-Credentials", "true");
            Response.End();
        }
    }

但无济于事。任何人都可以帮忙吗?

请注意,如果我删除代码以启用CORS,而是将以下设置添加到我的Web.config中,那么在本地运行所有内容时会出现此错误: -

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS" />
    <add name="Access-Control-Allow-Credentials" value="true"/>
    <add name="Access-Control-Allow-Headers" value="X-Requested-With, origin, content-type, accept" />
  </customHeaders>
</httpProtocol>

由于

1 个答案:

答案 0 :(得分:0)

我设法通过将Authorize属性添加到我从Angular2调用的两个控制器来解决这个问题。通过在我的Angular2应用程序的http调用中使用withCredentials,我还必须在我的控制器上添加Authorize属性以使其工作。我还必须在IIS上启用匿名身份验证以及集成/ Windows身份验证,以便将其用于所有工作

相关问题