How to do a cross domain json request with jquery and asp.net mvc web api - Digital Tool Factory blog How to do a cross domain json request with jquery and asp.net mvc web api - Digital Tool Factory blog

How to do a cross domain json request with jquery and asp.net mvc web api

So – I was trying to request some data from one server from another – not normally a big deal, but the data would vary depending on whether or not the user was logged in or not.  I thought just setting up CORS would work (I’m using asp.net mvc web api 2).  I thought a simple jquery .post or .get would do the job, but surprisingly the .get and .post do not send the auth cookie when making the request – you have to use the .ajax features of jQuery, as well as enabling the “SupportsCredentials” part of Cors – the relevant parts look like this

In your web api controller

[EnableCors(origins: “*”, headers: “*”, methods: “*”,  SupportsCredentials = true)]

Your javascript code should look like this

$.ajax({
url: ‘http://MyWebServiceDomain.com/api/v.1.1/SomeController/MyFeature’,
dataType: ‘json’,
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (authText) {
$(‘#authText’).html(authText);
}
});

 

Written By Steve French

 

Leave a Reply

Your email address will not be published. Required fields are marked *






Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.