api netcore 跨域支持_ASP.NET Core WebApi 跨域配置 Cors

使用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();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值