Let’s see how to allow web API to be called from JQuery.
Browser prevents a web page from making AJAX requests to another domain. This is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site.
But What will do if you create a web API to be called by other websites. You have to allow then to call your API. Cross Origin Resource Sharing (CORS) allows a server to come over this policy. You can allow specific origins to access your web API.
Let’s understand with an example.
Let’s create a Web API first : I am not going to spoon feed you to create web API. I hope you know how to create web API application. Great..
Let’s take a APIController :
using System.Web.Http.Cors;
[EnableCors(origins: "http://localhost:12081", headers: "*", methods: "*")]
public class ValuesController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
Ooops, what is EnableCors ?
You have to install a nuget package to get this. Write below command in package manager console :
Install-Package Microsoft.AspNet.WebApi.Cors
Next step to register CORS from global.asax :
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Yeah, Your web API is ready to be accessed from origin ‘http://localhost:12081’.
Do I have any option to allow multiple origin ?
Of course Yes. You can set number of origin by comma separated value like ‘http://localhost:12081, http://www.heros.com, http://www.xyss.com’. Or you can allow all origin by putting ‘*’
[EnableCors(origins: "*", headers: "*", methods: "*")]
Note : Don’t include forward slash at the end of url. E.g ‘http://localhost:12081/’
Now call API from JQuery :
jQuery.ajax({
type: "GET",
url: 'http://192.168.1.118:85/api/values',
success: function (data) {
alert(JSON.stringify(data));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
Hooray!! it’s working...