我的使用場景:
在本地建立了一個html文件踢涌,通過ajax訪問asp.net core 3.1提供的webapi服務(wù)黔龟。
在調(diào)試時,發(fā)現(xiàn)用html訪問拋了cors異常讨惩。
拋這樣的錯誤:
Access to XMLHttpRequest at 'http://localhost:52156/api/Person/1' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
jquery-1.10.2.min.js:23 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost:52156/api/Person/1 with MIME type text/plain.
在微軟網(wǎng)站
查到辟癌,asp.net core cors 3.1的做法如下 :
在Startup類里面:
1.添加
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins ,
builder => builder.AllowAnyOrigin()
/*
根據(jù)自己情況調(diào)整
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
如果同時打開 AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
會拋下面這個異常:
System.InvalidOperationException: Endpoint AnXin.DigitalFirePlatform.WebApi.Controllers.StaticPersonController.Get (AnXin.DigitalFirePlatform.WebApi) contains CORS metadata, but a middleware was not found that supports CORS.
Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...).
at Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingCorsMiddlewareException(Endpoint endpoint)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
*/
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddControllers();
}
3.Configure(IApplicationBuilder app, IHostingEnvironment env)方法里添加一行:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
//主要就是這兩行,但是要注意荐捻,這一行要在app.UseRouting 和 UseEndpoints 之間
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins);
});
}