WebApi series ~ Implement Cors access in WebApi

Source: Internet
Author: User

Preface

Cors is a hot technology, which is also reflected in Jiang Jinnan's blog. Cors simply means "cross-origin resource access, this access refers to asynchronous access implemented by Ajax. The image point is that A website A exposes some interface methods, for website B and website C, you can call the method of website A by sending the Xmlhttprequest request. For the xmlhttprequest encapsulated plug-ins, such as jquery's $. ajax allows developers to easily write AJAX asynchronous requests, including Get, Post, Put, and Delete requests.

Cors is not a new technology. It only processes HTTP request headers. In our Cors architecture, jsonp is encapsulated to allow developers to access jsonp, less code, more intuitive. (Jsonp has nothing to do with Json. It returns a Script response block from a URI. Therefore, JSONP itself has nothing to do with the domain name, while the traditional JSON uses xmlhttprequest, it cannot be accessed across domains by default)

Next, let's talk about jsonp encapsulation:

1. register the jsonp type. In the Application_Start method of global. asax

 GlobalConfiguration.Configuration.Formatters.Insert(,  EntityFrameworks.Web.Core.JsonpMediaTypeFormatter());

2. Compile the JsonpMediaTypeFormatter type to implement the response to the jsonp request, and add the specified information in the response stream, such as the callback method name.

                 Callback { ;   JsonpMediaTypeFormatter( callback = .Callback =  Task WriteToStreamAsync(Type type,  (.IsNullOrEmpty(  Task.FromResult<AsyncVoid>(<AsyncVoid> source =  TaskCompletionSource<AsyncVoid>  WriteToStream(Type type, = JsonSerializer.Create( (StreamWriter streamWriter =  StreamWriter(writeStream,  (JsonTextWriter jsonTextWriter =  JsonTextWriter(streamWriter) { CloseOutput = .Callback +   (request.Method !=  (request.GetQueryNameValuePairs().ToDictionary(pair =>=> pair.Value).TryGetValue(,   =  
Second, enable friendly cross-origin resource access for the specified domain name:

1. Register HttpHandler in global. asax so that it can perform secondary processing on HTTP processing. It can have two versions: synchronous and asynchronous. In this example, asynchronous implementation is implemented.

  GlobalConfiguration.Configuration.MessageHandlers.Add( EntityFrameworks.Web.Core.Handlers.CorsMessageHandler());

The following is the original MessageHandlers code to implement secondary processing of HTTP requests.

                 Task<HttpResponseMessage>            HttpMethod originalMethod = isPreflightRequest = method = request.Headers.GetValues(= === ==            CorsAttribute corsAttribute = actionDescriptor.GetCustomAttributes<CorsAttribute>().FirstOrDefault() ??<CorsAttribute> ( ==             IDictionary<, >= authorized = corsAttribute.TryEvaluate(request, = ==              (headers !=  && ( item  Task.FromResult<HttpResponseMessage>

2. Add the Cors feature to process domain names that can be accessed across domains, such as website B and website C.

         [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]   
Uri[] AllowOrigins { ; ErrorMessage { ; CorsAttribute( .AllowOrigins = (allowOrigins ?? []).Select(origin => TryEvaluate(HttpRequestMessage request, IDictionary<, >= origin = = request.Headers.GetValues(.ErrorMessage = = (= .ErrorMessage = IDictionary<, > origin = request.Headers.GetValues(<, > headers = Dictionary<, > headers.Add(, requestHeaders = request.Headers.GetValues( (! IsPreflightRequest( request.Method ==&& request.Headers.GetValues(&& request.Headers.GetValues(

3. The following describes how to add the access feature of a specified domain name for a specified API type.

    [CorsAttribute(, )]       }

The result of the example is as follows:

The jsonp and json methods are used respectively. Let's take a look at their response results.

As you can see, jsonp is implemented as a remote JS method call. The client initiates an HTTP request, which distinguishes multiple clients through the callback parameter (a string of random numbers, the callback requests of each client are different. They are processed by the server, and then the data is returned to the specified client through the random number of callback.

 

Thank you for reading this article!

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.