启用 ASP.NET Core 中的跨域请求 (CORS)
ASP.NET MVC 配置允许跨域访问
文档目录
.NET 文档
ASP.NET 文档
【注意:仅能限制ajax json请求,不能限制ajax jsonp请求,本地修改了host文件,配置了不同域名,已经反复测试证实。】
1、管理 NuGet 添加引用
Microsoft.AspNetCore.Cors
2、Startup.cs【使用命名的策略和中间件的 CORS,CORS 中间件处理跨域请求】
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
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
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 的替代方法】
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
namespace Web.Api.Controllers
{
[EnableCors("AllowSpecificOrigin")]
[Route("api/[controller]")]
[ApiController]
public class DefaultController : ControllerBase
{
// GET: api/Default
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/Default/alias
[HttpGet("{alias}")]
public Author Get(string alias)
{
return new Author { Id = 1, Name = alias, Age = 20 };
}
// GET api/Default/GetAuthor?id=100&alias=abc
[HttpGet("GetAuthor")]
public Author GetAuthor(int id, string alias)
{
return new Author { Id = id, Name = alias, Age = 20 };
}
// GET: api/Default/search?namelike=th
[HttpGet("Search")]
public IActionResult Search(string namelike)
{
var result = "result:" + namelike;
if (!result.Any())
{
return NotFound(namelike);
}
return Ok(result);
}
// GET api/Default/about
[HttpGet("About")]
public ContentResult About()
{
return Content("An API listing authors of docs.asp.net.");
}
// GET api/Default/version
[HttpGet("version")]
public string Version()
{
return "Version 1.0.0";
}
// POST: api/Default
[HttpPost]
public void Post([FromBody] string value)
{
string dt = DateTime.Now.ToShortDateString();
}
// PUT: api/Default/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
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>
</configuration>
<!--ProjectGuid: a654015f-f1f8-4467-8a05-bdd22227f48f-->
*
*
*
*
*
*
*