通过微软的cors类库,让ASP.NET Web API 支持 CORS
前言:因为公司项目需要搭建一个Web API 的后端,用来传输一些数据以及文件,之前有听过Web API的相关说明,但是真正实现的时候,感觉还是需要挺多知识的,正好今天有空,整理一下这周关于解决CORS的问题,让自己理一理相关的知识。
ASP.NET Web API支持CORS方式,据我目前在网上搜索,有两种方式
- 通过扩展CorsMessageHandle实现: http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-04.html
- 通过微软的 AspNet.WebApi.Cors 类库实现 http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#intro
本文主要是利用AspNet.WebApi.Cors 类库实现CORS,因为在选择的过程中,发现扩展的CorsMessageHandle会有一些限制,因为真正项目的HTTP Request 是Rang Request.
你需要了解的一些知识
- Web API 2.0 http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
- 同源策略与JSONP http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-01.html
- CORS http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-02.html
1.创建Web API (myservice.azurewebsites.net)
这个简单放上图:
1.1

1.2

1.3

1.4

1.5

1.6将下面的code替代原来的TestController
using System.Net.Http;using System.Web.Http;namespace WebService.Controllers{ public class TestController : ApiController { public HttpResponseMessage Get() { return new HttpResponseMessage() { Content = new StringContent("GET: Test message") }; } public HttpResponseMessage Post() { return new HttpResponseMessage() { Content = new StringContent("POST: Test message") }; } public HttpResponseMessage Put() { return new HttpResponseMessage() { Content = new StringContent("PUT: Test message") }; } }}
1.7 可以测试创建的Web API是否可以正常工作
2.创建Client端(myclilent.azurewebsites.net)
这也是可以简单上图:
2.1

2.2

2.3 找到 Client端的 Views/Home/Index.cshtml,用下面代码替代
<div> <select id="method"> <option value="get">GET</option> <option value="post">POST</option> <option value="put">PUT</option> </select> <input type="button" value="Try it" onclick="sendRequest()" /> <span id='value1'>(Result)</span></div>@section scripts {<script> var serviceUrl = 'http://myservice.azurewebsites.net/api/test'; // Replace with your URI. function sendRequest() { var method = $('#method').val(); $.ajax({ type: method, url: serviceUrl }).done(function (data) { $('#value1').text(data); }).error(function (jqXHR, textStatus, errorThrown) { $('#value1').text(jqXHR.responseText || textStatus); }); }</script>}
2.4用例外一个域名发布网站,然后进入Index 页面,选择 GET,POST,PUT 等,点击 Try it 按钮,就会发送请求到Web API, 因为Web API没有开启CORS,而通过AJAX请求,浏览器会提示 错误

3.Web API支持CORS
3.1打开VS,工具->库程序包管理器->程序包管理器控制台 ,输入下列命令:Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.0.0
注意 :目前Nuget 上面最新的版本是5.2.0 ,但是我测试,下载的时候,会有一些关联的类库不是最新的,System.Net.Http.Formatting 要求是5.2,我在网上找不带这dll,因此建议安装 :Microsoft.AspNet.WebApi.Cors 5.0就OK了。
Nuget 科普link: http://www.cnblogs.com/dubing/p/3630434.html

3.2 打开 WebApiConfig.Register 添加 config.EnableCors()
using System.Web.Http;namespace WebService{ public static class WebApiConfig { public static void Register(HttpConfiguration config) { // New code config.EnableCors(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }}
3.3 添加[EnableCors] 特性 到 TestController
using System.Net.Http;using System.Web.Http;using System.Web.Http.Cors;namespace WebService.Controllers{ [EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")] public class TestController : ApiController { // Controller methods not shown... }}
3.4回到Client端,这时再次发送请求,会提示成功信息,证明CORS已经实现了。

4.为[EnableCors]设置到 Action, Controller, Globally
4.1Action
public class ItemsController : ApiController{ public HttpResponseMessage GetAll() { ... } [EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")] public HttpResponseMessage GetItem(int id) { ... } public HttpResponseMessage Post() { ... } public HttpResponseMessage PutItem(int id) { ... }}
4.2Controller
[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]public class ItemsController : ApiController{ public HttpResponseMessage GetAll() { ... } public HttpResponseMessage GetItem(int id) { ... } public HttpResponseMessage Post() { ... } [DisableCors] public HttpResponseMessage PutItem(int id) { ... }}
4.3Globally
public static class WebApiConfig{ public static void Register(HttpConfiguration config) { var cors = new EnableCorsAttribute("www.example.com", "*", "*"); config.EnableCors(cors); // ... }}
5.[EnableCors]工作原理
要理解CORS成功的原理,我们可以来查看一下
跨域的请求
GET http://myservice.azurewebsites.net/api/test HTTP/1.1Referer: http://myclient.azurewebsites.net/Accept: */*Accept-Language: en-USOrigin: http://myclient.azurewebsites.netAccept-Encoding: gzip, deflateUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)Host: myservice.azurewebsites.net
当发送请求的时候,浏览器会将“Origin”的请求头发送给 服务端,如果服务端允许跨域请求,那么响应回来的请求头,添加“Access-Control-Allow-Origin”,以及将请求过来的 域名 的value添加到 Access-Control-Allow-Origin,浏览器接收到这个 请求头,则会显示返回的数据,否则,即使服务端成功返回数据,浏览器也不会接收
服务器的响应
HTTP/1.1 200 OKCache-Control: no-cachePragma: no-cacheContent-Type: text/plain; charset=utf-8Access-Control-Allow-Origin: http://myclient.azurewebsites.netDate: Wed, 05 Jun 2013 06:27:30 GMTContent-Length: 17GET: Test message
6.自定义CORS Policy Providers
6.1除了使用自带的[EnableCors]特性外,我们可以自定义自己的[EnableCors]。首先是要继承Attribute 和 ICorsPolicyProvider 接口
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]public class MyCorsPolicyAttribute : Attribute, ICorsPolicyProvider { private CorsPolicy _policy; public MyCorsPolicyAttribute() { // Create a CORS policy. _policy = new CorsPolicy { AllowAnyMethod = true, AllowAnyHeader = true }; // Add allowed origins. _policy.Origins.Add("http://myclient.azurewebsites.net"); _policy.Origins.Add("http://www.contoso.com"); } public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request) { return Task.FromResult(_policy); }}
实现后,可以添加自己定义的[MyCorsPolicy]
[MyCorsPolicy]public class TestController : ApiController{ .. //
6.2或者你也可以从配置文件中读取 允许的域名
public class CorsPolicyFactory : ICorsPolicyProviderFactory{ ICorsPolicyProvider _provider = new MyCorsPolicyProvider(); public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request) { return _provider; }} public static class WebApiConfig{ public static void Register(HttpConfiguration config) { config.SetCorsPolicyProviderFactory(new CorsPolicyFactory()); config.EnableCors(); // ... }}
通过微软的cors类库,让ASP.NET Web API 支持 CORS的更多相关文章
- 通过扩展让ASP.NET Web API支持W3C的CORS规范
让ASP.NET Web API支持JSONP和W3C的CORS规范是解决"跨域资源共享"的两种途径,在<通过扩展让ASP.NET Web API支持JSONP>中我们 ...
- 跨域资源共享(CORS)在ASP.NET Web API中是如何实现的?
在<通过扩展让ASP.NET Web API支持W3C的CORS规范>中,我们通过自定义的HttpMessageHandler自行为ASP.NET Web API实现了针对CORS的支持, ...
- 通过扩展让ASP.NET Web API支持JSONP
同源策略(Same Origin Policy)的存在导致了"源"自A的脚本只能操作"同源"页面的DOM,"跨源"操作来源于B的页面将会被拒 ...
- (转)通过扩展让ASP.NET Web API支持JSONP
原文地址:http://www.cnblogs.com/artech/p/3460544.html 同源策略(Same Origin Policy)的存在导致了“源”自A的脚本只能操作“同源”页面的D ...
- 支持Ajax跨域访问ASP.NET Web Api 2(Cors)的简单示例教程演示
随着深入使用ASP.NET Web Api,我们可能会在项目中考虑将前端的业务分得更细.比如前端项目使用Angularjs的框架来做UI,而数据则由另一个Web Api 的网站项目来支撑.注意,这里是 ...
- 通过扩展让ASP.NET Web API支持W3C的CORS规范(转载)
转载地址:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-04.html CORS(Cross-Origin Resource Shari ...
- CORS support for ASP.NET Web API (转载)
CORS support for ASP.NET Web API Overview Cross-origin resource sharing (CORS) is a standard that al ...
- 让ASP.NET Web API支持POST纯文本格式(text/plain)的数据
今天在web api中遇到了这样一个问题,虽然api的参数类型是string,但只能接收post body中json格式的string,不能接收原始string. web api是这样定义的: pub ...
- 让ASP.NET Web API支持$format参数的方法
在不使用OData的情况下,也可以让ASP.NET Web API支持$format参数,只要在WebApiConfig里添加如下三行红色粗体代码即可: using System; using Sys ...
随机推荐
- Codeforces Round #382 (Div. 2) D. Taxes 哥德巴赫猜想
D. Taxes 题目链接 http://codeforces.com/contest/735/problem/D 题面 Mr. Funt now lives in a country with a ...
- 使用 DJ Java Decompiler 将整个jar包反编译成源文件
使用 DJ Java Decompiler 将整个jar包反编译成源文件 所使用的软件是 DJ Java Decompiler 3.9. 下面是一个有用的参考文档,说明如何批量编译 http://ww ...
- 基于SlidePanelLayout实现ResideMenu
同步发表于http://avenwu.net/2015/02/24/custom_slide_panel_layout_as_reside_style_on_dribble_and_qq Fork o ...
- jquery.pjax.js bug问题解决集锦
jquery.pjax 是一个很好的局部刷新插件,但实际应用过程是还是会有很多小问题,部分问题解决如下: 1.pjax 局部加载时候,IE 存在缓存问题,很容易理解,pjax是通过jquery的aja ...
- Git + BeyondCompare
Mac 环境: 1. 安装 BeyondCompare 2. 配置 ~/.gitconfig [diff] tool = bcomp [merge] tool = bcomp [difftool &q ...
- StringUtilsd的isEmpty、isNotEmpty、isBlank、isNotBlank
1. public static boolean isEmpty(String str) 判断某字符串是否为空,为空的标准是 str==null 或 str.length()==0 下面是 Strin ...
- Swift基础--手势识别(双击、捏、旋转、拖动、划动、长按)
// // ViewController.swift // JieUITapGestureRecognizer // // Created by jiezhang on 14-10-4. // ...
- Flink 剖析
1.概述 在如今数据爆炸的时代,企业的数据量与日俱增,大数据产品层出不穷.今天给大家分享一款产品—— Apache Flink,目前,已是 Apache 顶级项目之一.那么,接下来,笔者为大家介绍Fl ...
- Haproxy配置支持https获取用户IP地址
global log 127.0.0.1 local0 chroot /var/lib/haproxy #chroot运行路径 pidfile /var/run/haproxy.pid #haprox ...
- FFRPC应用之Client/Server
摘要: Ffrpc 进行了重构,精简了代码,代码更加清晰简洁,几乎完美的达到了我的预想.接下来将写几遍文章来介绍ffrpc可以做什么.简单总结ffrpc的特性是: Ffrpc是c++ 网络通信库 全异 ...