.net core 跨域

1、管理 NuGet 添加引用
     Microsoft.AspNetCore.Cors

2、Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    var urls = Configuration["AppSetting:Cores"].Split(',');
 
    #region 跨域访问 .NET Core 2.X
    services.AddCors(options =>
    {
        options.AddPolicy(AllowSpecificOrigins, builder => { builder.WithOrigins(urls); });
    });
    #endregion
 
    #region 跨域访问 .NET Core 3.X
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin", builder =>
        {
            //builder.WithOrigins("https://localhost:44390", "http://0.0.0.0:3201").AllowAnyHeader();
            builder.WithOrigins(urls) // 允许部分站点跨域请求
            //.AllowAnyOrigin() // 允许所有站点跨域请求(net core2.2版本后将不适用)
            .AllowAnyMethod() // 允许所有请求方法
            .AllowAnyHeader() // 允许所有请求头
            .AllowCredentials(); // 允许Cookie信息
        });
    });

    #endregion 
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }  
    app.UseRouting(); 
 
    #region 跨域【UseCors必须放在UseRouting和UseEndpoints之间】
    app.UseCors("AllowSpecificOrigin");
    #endregion

 

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

3、appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AppSetting": {
    "Cores": "https://localhost:44390,http://0.0.0.0:3201"
  },

  "AllowedHosts": "*"

4、Controller【使用属性启用 CORS,[EnableCors] 属性提供了一种全局应用 CORS 的替代方法】

 [EnableCors("AllowSpecificOrigin")]
    [Route("api/[controller]")]
    [ApiController]
    public class DefaultController : ControllerBase
    {
        。。。。。
    }

5、Asp.NET Core api 部署在 IIS 上 405-Method Not Allowed
解决方法:在部署的目录中找到 web.config 文件,添加 runAllManagedModulesForAllRequests

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <modules runAllManagedModulesForAllRequests="false">
        <remove name="WebDAVModule" />
      </modules>
      <aspNetCore processPath=".\MobileNurse.WebAPI.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
.NET Core 中,可以使用中间件来处理跨域请求。下面是一些解决跨域问题的方法: 1. 使用 Microsoft.AspNetCore.Cors 中间件 使用 Microsoft.AspNetCore.Cors 中间件可以轻松地处理跨域请求。首先,您需要将 Microsoft.AspNetCore.Cors 包添加到项目中。然后,在 Startup.cs 文件的 ConfigureServices 方法中添加以下代码: ``` services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); }); }); ``` 此代码将创建一个名为“AllowAll”的策略,该策略允许来自任何来源的请求,允许任何 HTTP 方法和任何标头,还允许使用凭据。接下来,在 Startup.cs 文件的 Configure 方法中添加以下代码: ``` app.UseCors("AllowAll"); ``` 此代码将启用跨域请求处理。 2. 使用自定义中间件 您可以编写自己的中间件来处理跨域请求。以下是一个示例中间件: ``` public class CorsMiddleware { private readonly RequestDelegate _next; public CorsMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization"); if (context.Request.Method == "OPTIONS") { context.Response.StatusCode = 200; return; } await _next.Invoke(context); } } ``` 此中间件将在响应中添加必要的标头,以允许跨域请求。然后,将中间件添加到 Startup.cs 文件的 Configure 方法中: ``` app.UseMiddleware<CorsMiddleware>(); ``` 这将使您的自定义中间件用于处理跨域请求。 这些是解决 .NET Core跨域请求的两种常见方法。您可以根据需要选择其中一种方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值