发出 HTTP 请求时出现跨源错误

use*_*506 5 c# asp.net http cross-domain angular

当我从浏览器发出请求时,我的请求是有效的,但通过 Angular 9 应用程序我收到 401 错误。这是来自 chrome 的标题:

    Request URL: http://localhost:1234/api/Common/GetMy_List
Request Method: GET
Status Code: 401 
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, X-Token
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Allow-Origin: *
Cache-Control: private
Content-Length: 6069
Content-Type: text/html; charset=utf-8
Date: Wed, 06 Oct 2021 12:55:39 GMT
Server: Microsoft-IIS/10.0
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7
Connection: keep-alive
Host: localhost:1234
Origin: http://localhost:4200
Referer: http://localhost:4200/
sec-ch-ua: "Chromium";v="94", "Google Chrome";v="94", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36
Run Code Online (Sandbox Code Playgroud)

我有一个 Angular 9 项目,其中包含在 package.json 中声明的 proxy.conf.json 文件。该文件包含以下行:

{
  "/api/*": {
    "target": "http://localhost:1234",
    "secure": true,
    "logLevel": "debug",
    "changeOrigin": true
  }
}
Run Code Online (Sandbox Code Playgroud)

在服务器端有一个 asp.net api,在 global.asax 中包含以下几行:

 public void Application_BeginRequest(object sender, EventArgs e)
        {
            string httpOrigin = Request.Params["HTTP_ORIGIN"];
            if (httpOrigin == null) httpOrigin = "*";
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", httpOrigin);
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Token");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            if (Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.StatusCode = 200;
                var httpApplication = sender as HttpApplication;
                httpApplication.CompleteRequest();
            }
        }
Run Code Online (Sandbox Code Playgroud)

在 web.config 中:

  <system.webServer>
     <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
      </httpProtocol>
    <validation validateIntegratedModeConfiguration="false" />  
    <directoryBrowse enabled="false" />  
  </system.webServer>
 <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ImpersonateBehaviour">
          <clientCredentials>
            <windows allowedImpersonationLevel="Delegation" />
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService1" maxReceivedMessageSize="2147483647">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost/xxx.svc" behaviorConfiguration="ImpersonateBehaviour" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1" contract="Service1Ref.IService1" name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

Jay*_*yme 2

尝试将你的更改Application_BeginRequest为这个。当我尝试使用你的代码时,它在我的代码上失败了。下面的代码有效。

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
         HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
         HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept, X-Token");
         HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
         HttpContext.Current.Response.End();
    }
}
Run Code Online (Sandbox Code Playgroud)