.netcore3.1 設置可跨域

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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章