asp.net web api传送门:
asp.net web api 跨域请求支持十分简单,只需几步就搞定了
安装 Microsoft.AspNet.WebApi.Cors
打开NuGet包管理器,搜索cors,安装图中第一个包
配置
安装完成后打开WebApiConfig.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace leaveSystemAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// 开启Cors
config.EnableCors();
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "leave/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
然后在api控制器上使用特性进行相关配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace leaveSystemAPI.Controllers
{
[EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*", SupportsCredentials = true)]
public class testController : ApiController
{
public string Getname() {
return "123";
}
}
}
origins: 允许访问接口的域名
header:设置允许的请求标头
methods: 设置允许的请求方法
SupportsCredentials :是否允许 Web API 中的跨域凭据(包含cookie,以及 HTTP 身份验证方案)
前端需要设置withCredentials(跨域请求时是否需要使用凭证)为true
更加详细的用法:参考地址