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