asp.net core 3.1 解決跨域問題,親測可用

asp.net core 3.1 的跨域問題,若是沿用2.2版本的方法是行不通的。3.1版本對跨域問題要「嚴格」不少。javascript

微軟官方給個人解釋請以下網址:html

http://www.zyiz.net/tutorial/detail-4801.html java

 不能 同時打開git

AllowAnyOrigin()  .AllowAnyMethod()  .AllowAnyHeader()  .AllowCredentials());

 


不然會拋異常。web

 
// 會拋下面這個異常:
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)
 


那麼咱們就只開其中的1,2個就好了。如下是個人代碼,親測可用:ajax

一、Startup類裏先定義一個全局變量:api

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";//名字隨便起

二、ConfigureServices方法裏寫以下代碼:跨域

 
//找一找教程網原創文章

services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,

builder => builder.AllowAnyOrigin()

.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")

);

});

三、Configure方法裏添加中間件:

 

app.UseCors(MyAllowSpecificOrigins);

CORS 中間件必須配置爲在對 UseRouting 和 UseEndpoints的調用之間執行。 配置不正確將致使中間件中止正常運行。app

寫個ajax測試下:asp.net

 
<script type="text/javascript">
$(function () {
$.get("https://webapi-dev.zyiz.net/api/Health/POk", function (result) {
$("#mycontent").html(result);
});

});

</script>
 

 效果以下:

相關文章
相關標籤/搜索