Use the Microsoft cors class library to enable ASP. NET Web APIs to support CORS and cors class libraries.

Source: Internet
Author: User

Use the Microsoft cors class library to enable ASP. NET Web APIs to support CORS and cors class libraries.

Preface: A company project needs to build a backend of Web API to transmit some data and files. I have heard about Web API before, but when it is actually implemented, I feel that I still need a lot of knowledge. Today I am free to sort out this week's questions about how to solve CORS and let myself understand relevant knowledge.

ASP. NET Web APIs support the CORS method. Currently, I search online in either of the following ways:

  • Implementation of: http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-04.html by extending CorsMessageHandle
  • Http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api is implemented through Microsoft AspNet. WebApi. Cors class library

This article mainly uses the AspNet. WebApi. Cors class library to implement CORS, because during the selection process, it is found that the extended CorsMessageHandle has some restrictions, because the real project's HTTP Request is Rang Request.

Some 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-api
  • Same-source policy 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)

Here is a simple example:

1.1

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 created Web API works properly.

 

2. Create a Client (myclilent.azurewebsites.net)

This can also be simple:

2.1

<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 publish a website with an exception domain name, go to the Index page, select GET, POST, PUT, and so on, and click Try it to send the request to the Web API, the browser will prompt an error because CORS is not enabled for Web APIs and AJAX requests are sent.

Tool> library Package Manager> Package Manager Console, Enter the following command:Install-Package Microsoft. AspNet. WebApi. Cors-Version 5.0.0

Note: currently, the latest Nuget version is 5.2.0. However, during the test, some associated class libraries are not the latest, such as System. net. http. the Formatting requirement is 5.2. I cannot find this dll on the Internet. Therefore, we recommend that you install Microsoft. aspNet. webApi. cors 5.0 is OK.

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

3.2 openWebApiConfig. RegisterAddConfig. 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 Add[EnableCors]FeatureTestController

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 return to the Client and send the request again. A message indicating successful CORS is displayed, proving that CORS has been implemented.

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

[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.3 Globally

public static class WebApiConfig{    public static void Register(HttpConfiguration config)    {        var cors = new EnableCorsAttribute("www.example.com", "*", "*");        config.EnableCors(cors);        // ...    }}
5. [EnableCors] Working Principle

To understand the principle of successful CORS, let's take a look.

Cross-origin 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 sendingRequestWhen,BrowserThe"Origin"Request hair sentServerIf the server allows cross-origin requests, add"Access-Control-Allow-OriginAnd add the value of the requested domain nameAccess-Control-Allow-Origin,If the browser receives the request header, the returned data is displayed. Otherwise, the browser does not receive the returned data even if the server returns the data successfully.

Server Response

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. Customize CORS Policy Providers

6.1 apart from the built-in [EnableCors] feature, we can customize our [EnableCors]. First, inheritAttribute andICorsPolicyProvider Interface

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

After implementation, you can add your own defined [MyCorsPolicy]

[MyCorsPolicy]public class TestController : ApiController{    .. //

6.2 or you can read the allowed domain names 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();        // ...    }}

Q: Do I need to collect the coordinates of the local control points during CORS measurement? Is there an account connected to the CORS station to directly measure?

Yes, if CORS is used, the seven parameters have been converted and can be used directly.
 
Can I directly use the previously used coordinate parameters without using the control point correction instrument when using a measurement-type GPS system to test the CORS signal?

If you only want to test the signal strength of CORS, you do not need to correct it. However, it is recommended that you make correction so that you can check the accuracy of your instrument and the strength of the signal.

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.