通過微軟的cors類庫,讓ASP.NET Web API 支援 CORS

來源:互聯網
上載者:User

標籤:

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.