使用Cors 要引用 Microsoft.AspNetCore.Cors 命名空间
Startup.cs
customsetting.json
{
"Address": {
"allowUrl":
"http://localhost;http://localhost:8080;http://192.168.118.107;http://192.168.118.107:8080"
}
}
WebApi 使用:主要是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.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Cors;
using Newtonsoft.Json.Serialization;
using System.IO;
using Newtonsoft.Json;
namespace net_core_webapi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
//自定义配置文件目录
var basePath = Directory.GetCurrentDirectory();
CustomConfiguration = new ConfigurationBuilder().SetBasePath(basePath).AddJsonFile("customsetting.json", optional: true, reloadOnChange: true).AddEnvironmentVariables().Build();
}
public IConfiguration Configuration { get; }
public IConfiguration CustomConfiguration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//注册跨域服务 并指定允许请求的数据源
IConfiguration allowUrlSection = CustomConfiguration.GetSection("Address"); //"http://localhost,http://localhost:8080";
string allowurl = "http://localhost";
if (allowUrlSection != null)
{
allowurl = allowUrlSection["allowUrl"];
}
Console.WriteLine("allowurl:" + allowurl);
string[] allowArray = allowurl.Split(";", StringSplitOptions.RemoveEmptyEntries);
services.AddCors(Action => Action.AddPolicy("AllowSpecificOrigin", policy =>
policy.WithOrigins(allowArray)
.AllowAnyHeader()
.AllowAnyMethod() //如果不加此方法 默认只允许Get方式跨域请求
// .AllowCredentials() // 指定处理cookie
));
//注册MVC
services.AddMvc().AddJsonOptions(p =>
{
p.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; //指定序列化时间格式模式
p.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";//指定时间格式化
p.SerializerSettings.ContractResolver = new DefaultContractResolver(); //取消Json序列化的第一个字母小写
p.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;//忽略循环引用
});
}
// 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();
}
//启用跨域
app.UseCors("AllowSpecificOrigin");
app.UseMvc();
}
}
}