Asp.Net WebApi+Microsoft.AspNet.WebApi.Core 启用CORS跨域访问

WebApi中启用CORS跨域访问

1.安装 Nugget包Microsoft.AspNet.WebApi.Cors

 This package contains the components to enable Cross-Origin Resource Sharing (CORS) in ASP.NET Web API.

此包包含启用跨域资源共享的组件(CORS)在ASP.NET Web API。

目前版本是5.2.3

依赖项:

Microsoft.AspNet.WebApi.Core (>= 5.2.2 && < 5.3.0)

Microsoft.AspNet.Cors (>= 5.2.2)

 

2.WebApiApplication中启用跨域功能,默认是不可用的

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        //启用跨域
        /*
        * 注意,必须先启用跨域,然后,启用注册路由
        */
        GlobalConfiguration.Configuration.EnableCors();

        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

 

3.[EnableCors]在Controller或Action配置跨域方案

        //支持客户端凭据提交
        [EnableCors("http://localhost:51421", "*", "*", SupportsCredentials = true)]
        //[EnableCors("http://localhost:51421", "*", "*")]
        // [EnableCors("*", "*", "*")]
        public string GetOne()
        {
            return "1234";
        }

 客户端访问,带客户端凭据信息

$.ajax({
    url: apiUrl.getCookie('getone'),
    // url: apiUrl.getCookie('gettwo'),
    data: { age: 11 },
    xhrFields: {
        withCredentials: true  //支持附带详细信息
    },
    crossDomain: true,//请求偏向外域
    success: function (data) {
        alert(data);
    }
});

 

4.在controller中,指定[EnableCors]对所有的action,都起作用,然而,还可以单独指定到某个action

    [EnableCors("*", "*", "*")]
    public class CookieOneController : ApiController
    {
        //支持客户端凭据提交
        [EnableCors("http://localhost:51421", "*", "*", SupportsCredentials = true)]
        //[EnableCors("http://localhost:51421", "*", "*")]
        // [EnableCors("*", "*", "*")]
        public string GetOne()
        {
            return CookieHelper.GetString("username");
        }

        [HttpGet]
        [HttpPost]
        public string GetTwo()
        {
            return "1234";
        }
    }

 

更多:

https://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-22

Asp.Net WebApi 启用CORS跨域访问指定多个域名

Cors 跨域Access-Control-Allow-Origin

资料地址:

http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-05.html

 官方文档:

https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

posted @ 2015-12-31 17:07  天马3798  阅读(2927)  评论(0编辑  收藏  举报