通過微軟的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.1.

1.2

image

1.3

image

1.4

image

1.5

image

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

image

2.2

image

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請求,瀏覽器會提示 錯誤

image

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

image

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已經實現了。

image

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM