gpt4 book ai didi

c# - .NET Core UseCors() 不添加 header

转载 作者:可可西里 更新时间:2023-11-01 08:03:07 25 4
gpt4 key购买 nike

这将是 How does Access-Control-Allow-Origin header work? 的副本,但那里的方法也不适合我。我希望我只是遗漏了一些东西。

我试图在我的 .NET Core Web API 的响应中获取一个 Access-Control-Allow-Origin header ,我正在通过 AJAX 访问它。

我试过很多东西。除非另有说明,否则所有内容都在 Startup.cs 文件中。

方法一

根据 Microsoft Documentation :

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();
}

方法二

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 和方法上添加 [EnableCors("AllowWebApp")]

从 Postman 那里,我得到:

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 中试过了,得到了类似的标题。

如果重要的话,我尝试访问的方法有一个 Authorize 属性。但是那部分应该工作正常(我至少得到了很好的回应)

所以,我是不是遗漏了一些非常明显的东西,还是它坏了?我目前运行的是 1.1.0 版。


编辑添加 JS 和 Controller Stub

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();
}

Controller stub

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

最佳答案

问题是,当使用 Bearer 身份验证(或我想象的任何身份验证)时,它会添加一个 header “授权”,如果设置允许该 header ,服务器只会给出一个好的。

有两种方法可以解决这个问题,下面是唯一需要的代码。它位于 Web API 解决方案中 Startup.csConfigure() 方法中。

方法一:允许所有 header

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

方法 2:允许特定 header

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

额外的 header 是因为,根据文档:

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.

关于c# - .NET Core UseCors() 不添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41843973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com