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>
效果以下: