.net core 3.1 webapi解决跨域问题 GET DELETE POST PUT等

最近在弄一个项目,后端是.net core 3.1写的。 CORS也按照 官方文档 https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0 进行了配置。但是依然阻挡不了 DELETE,PUT 等方法出现的 CORS跨域问题。

下面来说一下我是如何解决的:

首先在startUp里配置好。

全局: readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

然后是ConfigureService 方法:
  public void ConfigureServices(IServiceCollection services)
        {
            //cors
            string[] corsUrl = Configuration.GetSection("ApplicationSettings:Cors").Get<string[]>();
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                    builder =>
                    {
                        builder
                .WithOrigins(corsUrl)
                .WithMethods("PUT", "DELETE", "GET","POST","PATCH")
                .SetIsOriginAllowed((host) => true)
                        .AllowAnyMethod()
                        .AllowCredentials()
                        .AllowAnyHeader();
            });
            });
            services.AddControllers();

然后是configure方法:

  app.UseRouting();
            //官網要求写在user Routing后,useAuthorization前.
            app.UseCors(MyAllowSpecificOrigins);

            app.UseAuthentication();

...........

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers()
                .RequireCors(MyAllowSpecificOrigins);
            });

这么配置好后,仍然是不行的。 GET 是好用的,但是DELETE等 还是报CORS错误。

下面高能,真正的解决方法来了:

修改发布文件的 web.config文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <modules>
        <remove name="WebDAVModule" />
      </modules>
      <handlers>
        <remove name="aspNetCore" />
        <remove name="WebDAV" />
        <!-- I removed the following handlers too, but these can probably be ignored for most installations -->
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\Jp.Api.Management.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

重要的是加粗部分,这个是之前没有的,有国外网友说是 "WebDAVModule"的问题。

好了,.net core3.1的CORS跨域问题至此全部解决。

 

上一篇:.NET 5应用程序中的跨域请求


下一篇:django跨域支持