angularjs CORS预检通道的CORS标头“Access-Control-Allow-Headers”中缺少标记“access-control-allow-headers”

snz8szmq  于 11个月前  发布在  Angular
关注(0)|答案(4)|浏览(140)

我有两个VS项目:一个暴露MVC5控制器,另一个是angular客户端。我希望angular客户端能够查询控制器。我读了很多线程,并尝试了以下方法:

  • 我在服务器的Web配置中添加了以下内容:
<system.webServer>
    <httpProtocol>
       <customHeaders>
            <clear />
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
<system.webServer>

字符串

  • 我在控制器的操作上创建并使用了以下过滤器:
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

  • 在angular客户端中,我创建了以下拦截器:
app.factory("CORSInterceptor", [
    function()
    {
        return {
            request: function(config)
            {
                 config.headers["Access-Control-Allow-Origin"] = "*";
                 config.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
                 config.headers["Access-Control-Allow-Headers"] = "Content-Type";
                 config.headers["Access-Control-Request-Headers"] = "X-Requested-With, accept, content-type";
                 return config;
            }
     };
}
]);

app.config(["$httpProvider", function ($httpProvider) {
    $httpProvider.interceptors.push("CORSInterceptor");
}]);


根据Firebug,这将导致以下请求:

OPTIONS //Login/Connect HTTP/1.1
Host: localhost:49815
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:50739
Access-Control-Request-Method: POST
Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-origin,content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache


以及以下回应:

HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Server: Microsoft-IIS/10.0
Public: OPTIONS, TRACE, GET, HEAD, POST
X-SourceFiles: =?UTF-8?B?RDpcVEZTXElVV2ViXEdhcE5ldFNlcnZlclxBU1BTZXJ2aWNlc1xMb2dpblxDb25uZWN0?=
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: *
Access-Control-Request-Headers: X-Requested-With, accept, content-type
Date: Tue, 01 Sep 2015 13:05:23 GMT
Content-Length: 0


Firefox仍然会通过以下消息阻止请求:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:49815//Login/Connect. (Reason: missing token 'access-control-allow-headers' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).

jaxagkaj

jaxagkaj1#

通常情况下,我读到的线程建议几个不必要的配置步骤,这造成了混乱。
为了简单的目的,从一个angular客户端发送一个跨站点请求到一个ASP控制器:

  • 不需要角拦截器。
  • 在服务器端不需要自定义过滤器。
  • 唯一的强制性修改是将其添加到服务器的web.config中
<system.webServer>
      <httpProtocol>
          <customHeaders>
              <clear />
              <add name="Access-Control-Allow-Origin" value="*" />
              <add name="Access-Control-Allow-Headers" value="Content-Type"/>
          </customHeaders>
     </httpProtocol>
</system.webServer>

字符串

yvfmudvl

yvfmudvl2#

问题是,有些浏览器还不允许Access-Control-Allow-Headers*插件。具体来说,Firefox 69和更早的版本不允许。请参阅https://bugzilla.mozilla.org/show_bug.cgi?id=1309358
因此,为了确保您在所有浏览器中获得正确的行为,您发送回的Access-Control-Allow-Headers值应该显式列出您实际需要从前端代码访问的所有头名称;例如,在问题中的情况下:Access-Control-Allow-Headers: Content-Type
一种无需硬编码所有头名称的方法是:让服务器端代码获取浏览器发送的Access-Control-Request-Headers请求头的值,并将其回显到服务器发送回的Access-Control-Allow-Headers响应头的值中。
或者使用一些现有的库来启用服务器的CORS。将Access-Control-Request-Headers请求头值返回到Access-Control-Allow-Headers响应头值是大多数CORS库通常会为您做的事情。

pb3s4cty

pb3s4cty3#

我在我的.net c# mvc应用程序和angular 8中的客户端应用程序中进行了尝试,但它不工作。

<httpProtocol>
  <customHeaders>
    <clear />
    <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
    <add name="Access-Control-Allow-Headers" value="Content-Type"/>
  </customHeaders>
</httpProtocol>

字符串
在global.axax.cs文件中,我还添加了

void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
    {
        Context.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
    }


但它不工作.在Chrome在响应头它确实显示为:
控制允许头:内容类型控制允许源:http://localhost:4200控制允许源:http://localhost:4200
但在请求头中显示为
访问控制请求头:访问控制允许源,内容类型,x-iphoneclientid
而它需要有
x-iphoneclientid:8E72FF50-548B
由于x-iphoneclientid是我在过滤器类中验证为

protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {

        if (request == null || request.RequestUri == null)
        {
            return null;
        }
        // Write your Authentication code here
        IEnumerable<string> monsterApiKeyHeaderValues = null;

        // Checking the Header values
        if (request.Headers.TryGetValues("x-iphoneclientid", out monsterApiKeyHeaderValues))


并且没有发现上述条件,因此拒绝该条件,并且该条件不到达控制器。
我甚至在我的控制器里加入了
[EnableCors(“",“",“*”)]
你能给我带路吗
谢谢

ufj5ltwl

ufj5ltwl4#

我也遇到了同样的问题,但其他答案对我不起作用,可能是由于使用了较新的框架。以下是Microsoft的官方文档,用于说明如何在2023 https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0中修复该问题。
在Program.cs文件中添加以下代码:

string myAllowSpecificOrigins = "myAllowSpecificOrigins";

builder.Services.AddCors(
    options => {
        options.AddPolicy(
            name: myAllowSpecificOrigins, policy => {
                policy.WithOrigins("https://localhost:44434")
                .AllowAnyHeader()
                .AllowAnyMethod();
            }
        );
    }
);

app.UseCors(myAllowSpecificOrigins);

字符串
这将允许指定的端口进行跨域请求。如果本地主机地址与您正在使用的端口不同,请确保将其替换为您正在使用的端口。在Program.cs文件中正确放置此代码也很重要。UseCors必须放置在UseRouting之后MapControllers之前(请参阅链接以获取更多详细信息和上下文示例)。

相关问题