让webapi支持CORS,可以跨域访问

1.在NuGet里搜索webapi找到下面的扩展,添加进项目里。

2.在Global.asax中添加一行代码

        protected void Application_Start()
        {
            //添加CORS的支持
            GlobalConfiguration.Configuration.EnableCors();

            //其他东西
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }    

3.在控制器顶部添加配置代码

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class Default1Controller : ApiController
*号代表允许所有。
origins 代表允许哪些站点访问你的api,如果你只允许百度访问你的api,就可以这样设置,如果有多个用,分开
[EnableCors(origins: "http://www.baidu.com,http://www.qq.com", headers: "*", methods: "*")]
headers,methods代表所允许的请求所允许的自定义包头和HTTP方法
 
posted @ 2014-08-26 20:02  十二月雨  阅读(463)  评论(0编辑  收藏  举报