前言:因为公司项目需要搭建一个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();        // ...    }}
 
 http://www.th7.cn/Program/net/201407/234213.shtml

通过微软的cors类库,让ASP.NET Web API 支持 CORS的更多相关文章

  1. 通过扩展让ASP.NET Web API支持W3C的CORS规范

    让ASP.NET Web API支持JSONP和W3C的CORS规范是解决"跨域资源共享"的两种途径,在<通过扩展让ASP.NET Web API支持JSONP>中我们 ...

  2. 跨域资源共享(CORS)在ASP.NET Web API中是如何实现的?

    在<通过扩展让ASP.NET Web API支持W3C的CORS规范>中,我们通过自定义的HttpMessageHandler自行为ASP.NET Web API实现了针对CORS的支持, ...

  3. 通过扩展让ASP.NET Web API支持JSONP

    同源策略(Same Origin Policy)的存在导致了"源"自A的脚本只能操作"同源"页面的DOM,"跨源"操作来源于B的页面将会被拒 ...

  4. (转)通过扩展让ASP.NET Web API支持JSONP

    原文地址:http://www.cnblogs.com/artech/p/3460544.html 同源策略(Same Origin Policy)的存在导致了“源”自A的脚本只能操作“同源”页面的D ...

  5. 支持Ajax跨域访问ASP.NET Web Api 2(Cors)的简单示例教程演示

    随着深入使用ASP.NET Web Api,我们可能会在项目中考虑将前端的业务分得更细.比如前端项目使用Angularjs的框架来做UI,而数据则由另一个Web Api 的网站项目来支撑.注意,这里是 ...

  6. 通过扩展让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 ...

  7. 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 ...

  8. 让ASP.NET Web API支持POST纯文本格式(text/plain)的数据

    今天在web api中遇到了这样一个问题,虽然api的参数类型是string,但只能接收post body中json格式的string,不能接收原始string. web api是这样定义的: pub ...

  9. 让ASP.NET Web API支持$format参数的方法

    在不使用OData的情况下,也可以让ASP.NET Web API支持$format参数,只要在WebApiConfig里添加如下三行红色粗体代码即可: using System; using Sys ...

随机推荐

  1. 进程间通信(IPC)介绍

    进程间通信(IPC,InterProcess Communication)是指在不同进程之间传播或交换信息. IPC的方式通常有管道(包括无名管道和命名管道).消息队列.信号量.共享存储.Socket ...

  2. 将ASP.NET Core应用程序部署至生产环境中(CentOS7)(转)

    阅读目录 环境说明 准备你的ASP.NET Core应用程序 安装CentOS7 安装.NET Core SDK for CentOS7. 部署ASP.NET Core应用程序 配置Nginx 配置守 ...

  3. struts1+spring+myeclipse +cxf 开发webservice以及普通java应用调用webservice的实例

    Cxf + Spring+ myeclipse+ cxf 进行  Webservice服务端开发 使用Cxf开发webservice的服务端项目结构 Spring配置文件applicationCont ...

  4. UnionPay,ChinaPay 最新 银联支付接口C#\Asp.net\MVC 版本

    1.概念普及 一.理解什么是UnionPay.ChinaPay 这两个概念如果搞不清楚,绝对够你瞎折腾一段时间的. UnionPay:中国银联,最大的机构:他本身也提供系统接口但都是B2B的,对于单个 ...

  5. Hadoop-Drill深度剖析

    1.概述 在<Hadoop - 实时查询Drill>一文当中,笔者给大家介绍如何去处理实时查询这样的业务场景,也是简略的提了一下如何去实时查询HDFS,然起相关细节并未说明.今天给大家细说 ...

  6. 【书单】book list

    正在看: [泡沫经济学].(日)野口悠纪雄 数学模型--姜启源 R in action Programming with R Scrapy Parallel R     准备看: Advanced.A ...

  7. 查看macbook是多少位

    Prince-2:~ snowinmay$ uname -aDarwin Prince-2.local 12.5.0 Darwin Kernel Version 12.5.0: Sun Sep 29 ...

  8. C++ Low level performance optimize

    C++ Low level performance optimize 1.  May I have 1 bit ? 下面两段代码,哪一个占用空间更少,那个速度更快?思考10秒再继续往下看:) //v1 ...

  9. .woff HTTP GET 404 (Not Found)

    原因:IIS没有添加woff字体的MIME类型,导致HTTP请求404 Not Found错误 解决办法: 1.在web.config中配置 <system.webServer> < ...

  10. nginx 常用配置说明

    一.location 配置 1.1 语法规则: location [=|~|~*|^~] /uri/ { … }= 开头表示精确匹配^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可 ...