在ASP.NET Web API中实现CORS(跨域资源共享)
2015-10-27 08:55
681 查看
默认情况下,是不允许网页从不同的域访问服务器资源的,访问遵循"同源"策略的原则。
会遇到如下的报错:
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类中配置如下:
在ApiController上设置CROS属性。
以上就实现了在ASP.NET Web API中的CROS。
会遇到如下的报错:
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。
相关文章推荐
- asp.net简单的注册或者登陆三层架构的例子
- asp.net三层架构详解
- 三种asp.net页面跳转的方法
- asp.net操作Word实现批量替换
- 关于asp.net[没有相关的源行]错误的解决方法及IIS安装问题
- 部署asp.net网站的小问题
- asp.net 中把txt文件导入 vs2010的sql2008数据库的一张表中【已测试,可以实现】
- asp.net跨页面传值之控件传递
- asp.net之cookie(设置css)
- ASP.NET控件缩写大全
- WCF寄宿IIS的asp.net 服务 基于Windows用户组的授权方式
- ConcurrentDictionary的使用
- ASp.Net Websocket 服务器端实现(三)
- ASp.Net Websocket 是什么(一)
- 注册asp.net 4.0 到iis
- ASP.NET MVC 3仿Server.Transfer效果的实现方法
- ASP固定比例裁剪缩略图的方法
- asp实现限制一个ip只能访问一次的方法
- Asp.net MVC中Html.Partial, RenderPartial, Action,RenderAction 区别和用法
- asp.net常见编码与解码