asp.net web api跨域请求支持

asp.net web api传送门:

  1. 跨域请求支持
  2. swagger在线接口文档
  3. cookie身份验证

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

更加详细的用法:参考地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值