$.ajax cross-domain request Web API

Source: Internet
Author: User

Wepapi really easy to use, no configuration files, a Apicontroller directly can work. But today with $.ajax cross-domain request is always get data, with fiddler A look did catch the data, but back to $.ajax function, directly triggered the error, no trigger success, even if the status code is 200. It is OK to use apiclient or direct browser access. . Finally find the answer in this article. http://code.msdn.microsoft.com/windowsdesktop/Implementing-CORS-support-a677ab5d

Reason

By default, to prevent CSRF from cross-site forgery attacks, a Web page is limited when it obtains data from a Web page in another domain. There are some ways to break this limit,JSONP is one. It uses the <script> tag plus a callback function. However, JSONP only supports the Get method. CORS(cross-origin Resource sharing) cross-domain resource sharing is a new header specification that allows the server-side to relax the cross-domain restrictions that can be toggled or not restricted across domain requests based on the header. It supports all HTTP request methods. Cross-domain resource requests come with an HTTP header:origin, and if the server supports Cors, the response comes with a header:access-control-allow-origin, and there are special requests. Using the HTTP "options" approach, hearder with Access-control-request-method or access-control-request-headers, The server responds with a hearder that requires access-control-allow-methods,access-control-allow-headers.

Realize

How to achieve cors, this uses the Message Handler. It can intercept and modify the request in the pipeline, with the following code:

  Public classCorshandler:delegatinghandler {Const stringOrigin ="Origin"; Const stringAccesscontrolrequestmethod ="Access-control-request-method"; Const stringAccesscontrolrequestheaders ="access-control-request-headers"; Const stringAccesscontrolalloworigin ="Access-control-allow-origin"; Const stringAccesscontrolallowmethods ="Access-control-allow-methods"; Const stringAccesscontrolallowheaders ="access-control-allow-headers"; protected OverrideTaskSendAsync (httprequestmessage request, CancellationToken CancellationToken) {BOOLIscorsrequest =request.            Headers.contains (Origin); BOOLIspreflightrequest = Request. Method = =httpmethod.options; if(iscorsrequest) {if(ispreflightrequest) {returnTask.factory.startnew{httpresponsemessage response=Newhttpresponsemessage (Httpstatuscode.ok); Response. Headers.add (Accesscontrolalloworigin, request.) Headers.getvalues (Origin).                        First ()); stringAccesscontrolrequestmethod =request. Headers.getvalues (Accesscontrolrequestmethod).                        FirstOrDefault (); if(Accesscontrolrequestmethod! =NULL) {Response.                        Headers.add (Accesscontrolallowmethods, Accesscontrolrequestmethod); }                        stringRequestedheaders =string. Join (", ", request.                        Headers.getvalues (accesscontrolrequestheaders)); if(!string. IsNullOrEmpty (requestedheaders)) {response.                        Headers.add (Accesscontrolallowheaders, requestedheaders); }                        returnresponse;                }, CancellationToken); }                Else                {                    return Base. SendAsync (Request, CancellationToken). Continuewith{Httpresponsemessage resp=T.result; Resp. Headers.add (Accesscontrolalloworigin, request.) Headers.getvalues (Origin).                        First ()); returnresp;                }); }            }            Else            {                return Base.            SendAsync (Request, CancellationToken); }        }    }

Then add in global:

protected void Application_Start (object  sender, EventArgs e)        {             GLOBALCONFIGURATION.CONFIGURATION.MESSAGEHANDLERS.ADD (new   Corshandler ());             Webapiconfig.register (globalconfiguration.configuration);        }

Script:

  $.ajax ({ //  URL: "http://localhost:11576/api/Values",  URL: "Http://localhost:39959/api/user/login?name=niqiu&am               p;pwd=123456 " "GET"  // contenttype: "Application/json;",                     success: function   (Result) {                alert (result.status); }, Error:  function   (xmlhttpreques T, Textstatus, Errorthrown) {alert ( "Error!)                XMLHttpRequest: "+ Xmlhttprequest.status); }            });

This access is OK.

$.ajax cross-domain request Web API

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.