asp.net core 3.1 solve cross-domain issues, pro-test available

asp.net core cross-domain issues 3.1, 2.2 version of the method followed if does not work. Version 3.1 should "strictly" for cross-domain issues a lot.

Microsoft officials explained to me please the following website:

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

 You can not open

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

 


Otherwise it will throw an exception.

// 会抛下面这个异常:
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)

 


Then we just open them or two on the line. The following is my code, pro-test available:

1, Startup class to define a global variable:

Readonly  String MyAllowSpecificOrigins = " _myAllowSpecificOrigins " ; // name easily play

2, ConfigureServices method to write the following code:

// look for tutorials Network original article 

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

Builder => builder.AllowAnyOrigin () 

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

); 

});

 


3, Configure method in adding middleware:

 

app.UseCors(MyAllowSpecificOrigins);

 

CORS middleware must be configured to be performed between calls to UseRouting and UseEndpoints of. Middleware is not configured correctly will lead to stop functioning properly.

 

Ajax write the next test:

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

});

</script>

 Results are as follows:

Guess you like

Origin www.cnblogs.com/puzi0315/p/12484513.html