.NET Core UseCors()不添加标头 [英] .NET Core UseCors() does not add headers

查看:613
本文介绍了.NET Core UseCors()不添加标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这将是 Access-Control-Allow如何进行的重复-Origin标头有效吗?,但是那里的方法对我也不起作用.我希望我只是想念一些东西.

This would be a duplicate of How does Access-Control-Allow-Origin header work?, but the method there also isn't working for me. I'm hoping I'm just missing something.

我试图从我通过AJAX访问的.NET Core Web API的响应中获取Access-Control-Allow-Origin标头.

I am trying to get a Access-Control-Allow-Origin header in my response from my .NET Core Web API, which I am accessing via AJAX.

我尝试了几件事.除非另有说明,否则所有内容都位于Startup.cs文件中.

I have tried several things. All, unless noted otherwise, have been in the Startup.cs file.

方法1

根据 Microsoft文档:

public void ConfigureServices(IServiceCollection services)
{
    // Add database
    services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection")));

    // Add the ability to use the API with JSON
    services.AddCors();

    // Add framework services.
    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            serviceScope.ServiceProvider.GetService<DbContext>().Database.Migrate();
            serviceScope.ServiceProvider.GetService<DbContext>().EnsureSeedData();
        }
    }

    app.UseCors(builder => builder.WithOrigins("https://localhost:44306").AllowAnyMethod());

    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
        Audience = Configuration["Authentication:AzureAd:Audience"],
    });

    app.UseMvc();
}

方法2

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddCors(options => options.AddPolicy("AllowWebApp",
        builder => builder.AllowAnyMethod()
                          .AllowAnyMethod()
                          .AllowAnyOrigin()));
                          //.WithOrigins("https://localhost:44306")));

    // ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // ...

    app.UseCors("AllowWebApp");

    // ...
}

我还尝试在Controller和Method上都添加[EnableCors("AllowWebApp")].

I've also tried adding [EnableCors("AllowWebApp")] on both the Controller and Method.

从邮递员那里,我得到:

From Postman, I get:

内容编码→gzip
内容类型→文本/纯文本; charset = utf-8
日期→2017年1月25日星期三04:51:48 GMT
服务器→Kestrel
状态→200
变化→接受编码
x-技术支持→ASP.NET
x源文件→=?UTF-8?B?[已删除]

content-encoding → gzip
content-type → text/plain; charset=utf-8
date → Wed, 25 Jan 2017 04:51:48 GMT
server →Kestrel
status → 200
vary → Accept-Encoding
x-powered-by → ASP.NET
x-sourcefiles → =?UTF-8?B?[REDACTED]

我也在Chrome浏览器中尝试过,并获得了相似的标题.

I've also tried it in Chrome, and gotten similar headers.

如果有关系,我尝试访问的方法具有Authorize属性.但是那部分应该工作正常(我至少得到了很好的答复)

If it matters, the method I'm trying to access has an Authorize attribute on it. But that part should be working fine (I'm at least getting a good response)

那么,我是否错过了很明显的东西,或者这个东西坏了?我当前正在运行版本1.1.0.

So, am I missing something very obvious, or did this get broken? I'm currently running version 1.1.0.

编辑添加JS和Controller存根

function getContactPreviews(resultsCallback) {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = () => {
        if (xmlhttp.readyState == XMLHttpRequest.DONE && xmlhttp.status == 200) {
            resultsCallback(JSON.parse(xmlhttp.response));
        }
    }

    xmlhttp.open("GET", "https://localhost:44357/api/User/ContactsPreview", true);
    xmlhttp.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("AuthorizationToken"));
    xmlhttp.send();
}

控制器存根

[Authorize]
[Route("api/[controller]")]
public class UserController : ApiController
{
    [HttpGet(nameof(ContactsPreview))]
    [EnableCors("AllowWebApp")]
    public IEnumerable<Customer> ContactsPreview()
    {
        // ...
    }
}

推荐答案

问题是,在使用Bearer身份验证(或我想象的任何一种)时,它会添加标头"Authorization",并且服务器只会给出该设置允许该标头.

The problem is that when using Bearer authentication (or any I would imagine), it adds a header "Authorization", and the server will only give an okay if the setup allows for that header.

有两种方法可以解决此问题,下面是仅 代码.它位于Web API解决方案的Startup.cs中的Configure()方法中.

There's two ways to solve the problem, and below is the only code needed. It goes in the Configure() method in Startup.cs in the Web API solution.

方法1::允许所有标头

app.UseCors(builder => builder.WithOrigins("https://localhost:44306")
                                .AllowAnyMethod()
                                .AllowAnyHeader());

方法2:允许特定的标题

app.UseCors(builder => builder.WithOrigins("https://localhost:44306")
                              .AllowAnyMethod()
                              .WithHeaders("authorization", "accept", "content-type", "origin"));

多余的标题是因为,根据文档:

The extra headers are because, per the documentation:

浏览器在设置Access-Control-Request-Headers的方式上并不完全一致.如果将标头设置为除"*"以外的其他任何内容,则应至少包括"accept","content-type"和"origin",以及要支持的所有自定义标头.

Browsers are not entirely consistent in how they set Access-Control-Request-Headers. If you set headers to anything other than "*", you should include at least "accept", "content-type", and "origin", plus any custom headers that you want to support.

这篇关于.NET Core UseCors()不添加标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆