.net core webapi搭建(2)跨域

Core WebAPI中的跨域处理

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

如图所示

修改 ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    //配置跨域处理
    services.AddCors(options =>
    {
        options.AddPolicy("any", builder =>
        {
            builder.AllowAnyOrigin() //允许任何来源的主机访问
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials();//指定处理cookie
        });
    });
}

修改Controller

[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);
    }
}

  注意是这个玩意:

[EnableCors("any")]

打完收工

猜你喜欢

转载自www.cnblogs.com/Extnet/p/9626719.html