- 参考资料:
Enable Cross-Origin Requests (CORS) in ASP.NET Core
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1 - 基础环境
第三方引用: Microsoft.AspNetCore.Cors
前后台分离架构
使用前后端完全分离的架构,首先遇到的问题肯定是跨域访问。前后端可能不在同个server上,即使前后端处在同个server上,由于前后端完全分离,前后端使用的端口号也可能是不一样的,所以必须解决跨域访问。
API服务(webapi)添加cors
dotnet add package Microsoft.AspNetCore.Cors
全局设置跨域CORS
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace chapter1_webapi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//添加跨域访问策略
//注意这句好放在最后
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigin",
builder => builder.WithOrigins("*"));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
//启用跨域策略
app.UseCors("AllowAllOrigin");
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
其实开启CORS就是在返回客户端的HTTP头中增加一个字段
Response.Headers.Add("Access-Control-Allow-Origin","*");