jquery cross-domain call ASP.net Web API example

Source: Internet
Author: User
Tags static class

Objective

The ASP.net Web API is a lightweight Web service that has cross-domain problems when the Web APIs and Web programs are not deployed in the same domain, and the interface that uses jquery to implement the calling API. Here are two ways to solve the problem of the jquery call API Cross-domain.

Environment

iis:iis8.0
vs:vs2013
. Net framework:4.5
The first of these methods

Microsoft provides a cross-domain approach at the server side, with detailed steps to refer to the links below:

Http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Here's a few steps to summarize:

1, using the NuGet command install-package Microsoft.AspNet.WebApi.Cors installation dependencies;

2, the Webapiconfig class changes as follows, this class in the App_start directory.

public static class Webapiconfig
{
    public static void Register (Httpconfiguration config) br>     {
       //Web API Configuration and Services
        //The following behavior adds code
        config across a domain. Enablecors ();
       //Web API routes
        Config. Maphttpattributeroutes ();

Config. Routes.maphttproute (
Name: "Defaultapi",
Routetemplate: "Api/{controller}/{id}",
defaults:new {id = routeparameter.optional}
);
}
}
3, add the features on the controller of the API, as follows:

[Enablecors (Origins: "*", Headers: "*", Methods: "*")]
[Routeprefix ("Api/pro")]
public class Projectfilesapicontroller:apicontroller
{
Origins: Access to the client's address of the API, such as HTTP://LOCALHOST:8001, if multiple can be separated by commas, set to * to indicate that any client can access.

The second method

The second method is relatively simple, just modify the configuration file.

The configuration file code is as follows:

  <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 "/>
<directorybrowse enabled= "true"/>
</system.webServer>
Problem

Both of the above methods can achieve a cross-domain effect, but both of these methods only support Ie10+,chrome. To support browsers below IE10, you need to set the Cross-domain properties of jquery before invoking the following code:

Function Corstest () {
   //setting JQuery support cross-domain
    jQuery.support.cors = true;
& nbsp;   $.ajax ({
        URL: "http://localhost:8010/api/pro/ Empty ",
        Type:" POST ",
         DataType: "JSON",
        success:function (data) {
             alert (data);
       },
        error:function (A {
            alert (a);
       }
   });
}

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.