Web API cross-domain request, Ajax cross-domain call WEBAPI

Source: Internet
Author: User

1. A cross-domain problem occurs only when JavaScript initiates an Ajax call, or when Silverlight initiates a service invocation, because the browser is given a lower permission for both requests, usually allowing only the resources in the domain to be called. Unless the target server explicitly tells it to allow cross-domain calls. Suppose our page or application is already on the http://www.test1.com, and we intend to extract the data from the http://www.test2.com request. In general, if we use AJAX directly to request will fail, the browser will also return "source mismatch" error, " cross-domain " is also the origin.

2. What is cross-domain?

JavaScript is not allowed to invoke objects of other pages across domains for security reasons. Generally, the cross-domain is divided into the following categories: On a cross-domain issue, the domain is only identified by the "header of the URL" and does not attempt to determine whether the same IP address corresponds to two domains or two domains on the same IP. 3. When initiating Ajax cross domain calls to a service written by ASP. NET MVC or the ASP. NET Web API, an inaccessible condition occurs.The following error message appearsLet's explain here. Access-control-allow-origin is a server-side return response header defined in HTML5 that addresses cross-domain permissions issues for resources such as fonts. When Access-control-allow-origin is followed by a URL or *, if it is a URL it will only allow requests from that URL, * the request for any domain is allowed for example: header (' Access-control-allow-origin: Http://A.abc.com ') | | The header (' access-control-allow-origin:* ') means that you can only be accessed if the requested resource is allowed to cross the domain. So how do we set the Access-control-allow-origin? 4, the first is to use JSONP to obtain cross-domain data, and WEBAPI itself is not support JavaScript callbackcompare the differences between JSON and JSONP formats:JSON format:
{    "message": "Get Succeeded",    "state": "1",    "result": {"name": "Workgroup 1", "id": 1, "description": "11"}}
JSONP format:
Callback ({    "message": "Get Succeeded",    "state": "1",    "result": {"name": "Workgroup 1", "id": 1, "description": "11"}})

See the difference, in the URL callback to the background of the parameter is God horse callback is God horse, jsonp than JSON outside there is a layer, callback ().

Just to register a jsoncallbackattribute to the global, you can determine whether access to the interface is a cross-domain, or non-cross-domain, normal return.

Because our interface may be used to interface to the mobile (Android, IOS), or to the Web site, it is possible to consider cross-domain issues.

   GLOBALCONFIGURATION.CONFIGURATION.FILTERS.ADD (New Jsoncallbackattribute ());
public class Jsoncallbackattribute:actionfilterattribute    {        Private const string callbackqueryparameter = " Callback ";        public override void OnActionExecuted (Httpactionexecutedcontext context)        {            var callback = string. Empty;            if (Isjsonp (out callback))            {                var jsonbuilder = new StringBuilder (callback);                Jsonbuilder.appendformat ("({0})", Context. Response.Content.ReadAsStringAsync (). Result);                Context. Response.content = new Stringcontent (jsonbuilder.tostring ());                Context. Response.content = new Stringcontent ("C (\" A\ ")");            }            Base. onactionexecuted (context);        }        private bool Isjsonp (out string callback)        {            callback = system.web.httpcontext.current.request.querystring[ Callbackqueryparameter];            Return!string. IsNullOrEmpty (callback);        }

Combined with the following picture is not difficult to open, the requested address brought back, callback parameter identification.

Of course, can also be used to solve cross-domain problems of the jquery plug-in-jquery-jsonp, the first method of the foundation, the use of JSONP plug-in is relatively simple, server-side code without any changes.

5, the server directly modify the configuration file, personally think this way better, after all, we write the API is public, security access control or through other means to ensure.

For ASP. NET MVC, just add the following in Web. config

<system.webServer>

<customHeaders>

<add name= "Access-control-allow-origin" value= "*"/>

<add name= "Access-control-allow-headers" value= "Content-type"/>

<add name= "Access-control-allow-methods" value= "GET, POST, PUT, DELETE, OPTIONS"/>

</customHeaders>

<remove name= "extensionlessurlhandler-integrated-4.0"/>

<remove name= "Optionsverbhandler"/>

<remove name= "Traceverbhandler"/>

<add name= "extensionlessurlhandler-integrated-4.0" path= "*." verb= "*" type= " System.Web.Handlers.TransferRequestHandler "precondition=" integratedmode,runtimeversionv4.0 "/>

</system.webServer>

In addition to the above settings, for the ASP. NET Web API, you need to add a special design that adds an options method to each Apicontroller, but does not need to return anything.

public string Options ()

{

return null; HTTP response with empty body

}

6, also useful cors ( cross-domain resource sharing, Cross-origin Resource sharing) to solve, cors defines a cross-domain access mechanism, you can enable Ajax to achieve cross-domain access. CORS allows a network application on one domain to submit cross-domain AJAX requests to another domain. This is very simple to implement, and only one response header is sent by the server.

Hander () settings,"*" indicates that any domain is allowed to submit requests to our server

  You can also set the specified domain name, such as the domain name http://www.test2.com, then allow requests from this domain name :

This is not carefully studied, in fact, with the above configuration file, almost, is to set the response header. This article is a combination of many other authors ' articles: http://www.cnblogs.com/chenxizhang/p/3821703.htmlhttp://www.cnblogs.com/sunxucool/p/3433992. Htmlhttp://www.cnblogs.com/darren_code/p/cors.html

Web API cross-domain request, Ajax cross-domain call WEBAPI

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.