asp.net core 3.1 的跨域問題,如果沿用2.2版本的方法是行不通的。3.1版本對跨域問題要“嚴格”很多。
微軟官方給我的解釋請如下網址:
http://www.zyiz.net/tutorial/detail-4801.html
不能 同時打開
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)
那么我們就只開其中的1,2個就行了。以下是我的代碼,親測可用:
1、Startup類里先定義一個全局變量:
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";//名字隨便起
2、ConfigureServices方法里寫如下代碼:
//找一找教程網原創文章 services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, builder => builder.AllowAnyOrigin() .WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS") ); });
3、Configure方法里添加中間件:
app.UseCors(MyAllowSpecificOrigins);
CORS 中間件必須配置為在對 UseRouting 和 UseEndpoints的調用之間執行。 配置不正確將導致中間件停止正常運行。
寫個ajax測試下:
<script type="text/javascript"> $(function () { $.get("https://webapi-dev.zyiz.net/api/Health/POk", function (result) { $("#mycontent").html(result); }); }); </script>
效果如下: