美文网首页
Asp.Net Core WebAPI 跨域处理

Asp.Net Core WebAPI 跨域处理

作者: 溪桥路转 | 来源:发表于2018-07-29 15:29 被阅读0次

一、Core WebAPI中的跨域处理

  1. 在使用WebAPI项目的时候基本上都会用到跨域处理
  2. Core WebAPI的项目中自带了跨域Cors的处理,不需要单独添加程序包


    自带了跨域Cors的处理

使用实例

  1. 全局配置中启用跨域处理,命名为‘any’,任何都可以访问
    在Startup.cs中添加配置
public void ConfigureServices(IServiceCollection services)
{
    //配置跨域处理
    services.AddCors(options =>
    {
        options.AddPolicy("any", builder =>
        {
            builder.AllowAnyOrigin() //允许任何来源的主机访问
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials();//指定处理cookie
        });
    });
}
  1. 在控制器或Action的方法注释上使用对应名称的 跨域规则[EnableCors("any")]
 [Route("api/[controller]")]
    [ApiController]
    [EnableCors("any")] //设置跨域处理的 代理
    public class UserController : ControllerBase
    {
         // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<User>> Get()
        {
            Conn mysqlGet = new Conn();
            return mysqlGet.UserList();
        }
    }

注:如果在控制器上指定,则控制器内 所有的Action都有对应的跨域限制。

三 、跨域时,Cookie的访问

  1. 后台通过HttpContext上下文可以直接操作Cookie
[Produces("application/json")]
[Route("api/CookieOne")]
[EnableCors("any")]
public class CookieOneController : Controller
{
    //后台设置Cookie 
    [HttpPut]
    public IActionResult Add()
    {
        ControllerContext.HttpContext.Response.Cookies.Append("name", "中文 ,张三丰");
        return Ok(new { msg = "设置成功" });
    }

    //后台获取Cookie,特别 说明对于基础类型的返回值,默认JQuery的ajax解析失败,最好返回IActionResult 
    [HttpGet]
    public IActionResult Get()
    {
        string result = HttpContext.Request.Cookies["url"];
        return Content(result);
    }
}
  1. 前台JQuery的ajax请求,需要携带withCredentials才会将cookie的值保存到客户端
var example1 = new Vue({
    el: '#example1',
    data: {
        name: '空',
        url: '空'
    }
});
//1.后台添加cookie
function addOne() {
    $.ajax({
        url: urlHelper.getApi('cookieone'),
        type: 'put',
        xhrFields: {
            withCredentials:true //配置http跨域请求中携带cookie
        },
        success: function (data) {
            console.info(data);
            //前台获取cookie
            var name = Cookies.get('name');
            console.info(name);
            example1.name = name; //Vue中修改双向绑定可以通过Vue实例进行,不需要再次通知页面(和AngularJs不同)
        }
    });
}
addOne();
//2.前台添加Cookie 后台获取
function getOne()
{
    Cookies.set('url', 'http://www.gongjuji.net/');


    $.ajax({
        url: urlHelper.getApi('cookieone'),
        type: 'get',
        contentType: 'application/json',
        xhrFields: {
            withCredentials: true //配置http跨域请求中携带cookie
        },
        success: function (data) {
            console.info(data);
            example1.url = data;
        }
    });
}
getOne();

相关文章

网友评论

      本文标题:Asp.Net Core WebAPI 跨域处理

      本文链接:https://www.haomeiwen.com/subject/mpwzmftx.html