Let the ASP. NET Web API support cors through the Microsoft Cors Class Library

Source: Internet
Author: User

Preface : Because the company project needs to build a Web API backend, used to transfer some data and files, before the Web API to listen to the relevant instructions, but the real implementation of the time, the feeling still need a lot of knowledge, just today is free, tidy up this week to solve the problem of cors , so that you have a reason for the relevant knowledge.

The ASP. NET WEB API supports Cors mode, as far as I am currently searching online, there are two ways

    • By extending the Corsmessagehandle implementation: http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-04.html
    • Through Microsoft's AspNet.WebApi.Cors class library implementation http://www.asp.net/web-api/overview/security/ Enabling-cross-origin-requests-in-web-api#intro

This article mainly uses the AspNet.WebApi.Cors class library to implement Cors, because in the process of selection, it is found that the extended corsmessagehandle will have some limitations because the HTTP request for the real project is the rang request.

Some of the knowledge you need to know
    • Web API 2.0 Http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-a Pi
    • Homologous strategy and 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. Create a Web API (myservice.azurewebsites.net)

This simply puts:

1.1

1.2

1.3

1.4

1.5

1.6 Replace the following code with the original 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 You can test whether the Web API you are creating works

2. Create client side (myclilent.azurewebsites.net)

This can also be simple:

2.1

2.2

2.3 Locate the client side of the views/home/index.cshtml and replace it with the following code

<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 With the exception of a domain name publishing site, and then go to the index page, select Get,post,put, and so on, click the Try it button, will send the request to the Web API, because the Web API does not open cors, and through the AJAX request, the browser will prompt error

3.Web API Support Cors

3.1 Open vs, tools ---Library Package Manager, Package Manager console, enter the following command:install-package microsoft.aspnet.webapi.cors-version 5.0.0

Note: Currently nuget above the latest version is 5.2.0, but I test, download, there will be some associated class library is not up-to-date, System.Net.Http.Formatting requirements is 5.2, I find this DLL on the Internet, so it is recommended to install : Microsoft.AspNet.WebApi.Cors 5.0 is OK.

Nuget Popular link:http://www.cnblogs.com/dubing/p/3630434.html

3.2 Open webapiconfig.register Add 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 Adding [enablecors] attributes to 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 Back to the client side, then send the request again, will prompt the success of information, to prove that Cors has been implemented.

4. Set [Enablecors] to 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 Enab Lecorsattribute ("www.example.com", "*", "*");        Config. Enablecors (cors);        // ...    }}
5.[enablecors] how it works

To understand the principle of cors success, we can look at

Cross-Domain requests

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

When the request is sent, the browser sends the "Origin" request hair to the server, if the server allows cross-domain requests, then responds back to the request header, adding " Access-control-allow-origin", and add the value of the requested domain name to the access-control-allow-origin, the browser receives the request header, The returned data is displayed, otherwise the browser will not receive the data even if the server has successfully returned

Response of the server

http/1.1 Okcache-control:no-cachepragma:no-cachecontent-type:text/plain; charset=utf-8access-control-allow-origin:http://myclient.azurewebsites.netdate:wed, June 2013 06:27:30 Gmtcontent-length:17get:test message
6. Custom Cors Policy Providers

6.1 In addition to using the [enablecors] feature, we can customize our own [enablecors]. The first is to inherit the Attribute and Icorspolicyprovider interfaces

[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);}    }

Once implemented, you can add your own defined [mycorspolicy]

[Mycorspolicy]public class testcontroller:apicontroller{.    //

6.2 or you can read the allowed domain name from the configuration file

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

Let the ASP. NET Web API support cors through the Microsoft Cors Class Library

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.