在ASP.NET Web API中实现CORS(跨域资源共享)

 

默认情况下,是不允许网页从不同的域访问服务器资源的,访问遵循"同源"策略的原则。

 

会遇到如下的报错:


XMLHttpRequest cannot load http://localhost:49705//api/products. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:49729' is therefore not allowed access.

 

初始或源域名是:http://localhost:49729/
请求产品的域名是:http://localhost:49705//api/products

 

由于端口号不一致,所以,在"同源"策略下,服务器资源是被禁止访问的,会报错。


ASP.NET Web API为我们提供了实现CORS(跨域资源共享)的解决方案。


首先通过NuGet安装:microsoft asp.ent web api 202 cross-origin support


在WebConfig类中配置如下:

 

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
       ...

        // Web API 路由
        config.MapHttpAttributeRoutes();

        //全局允许CROS
        config.EnableCors();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );


    }
}

 

在ApiController上设置CROS属性。

 

[EnableCorsAttribute("http://localhost:49729","*","*")]
public class ProductsController : ApiController
{
...
}

 

以上就实现了在ASP.NET Web API中的CROS。

 

posted @ 2015-10-27 08:55  Darren Ji  阅读(779)  评论(4编辑  收藏  举报

我的公众号:新语新世界,欢迎关注。