Reputation: 4265
I have read a few articles detailing how to use JSONP with MVC4 (i am using the RC version) and the new Web Api. I am trying to perform a cross-domain request.I have no idea what I am doing wrong. My controller is inheriting from the ApiController class in MVC4. I tried Rick Strahl's implementation and a few others. Here is my example method:
public string StartTracking(string apiKey, DomainTracking domainTracking)
{
var user = _userService.GetByApiKey(apiKey);
if(user != null)
{
var domain = user.Domains.FirstOrDefault(d => d.Name.ToLower() == domainTracking.Domain.Name.ToLower());
if(domain != null)
{
domainTracking.DomainId = domain.Id;
domainTracking.Domain = domain;
domainTracking.CreatedById = user.Id;
domainTracking.ModifiedById = user.Id;
var newDomainTracking = _domainTrackingService.Create(domainTracking);
return newDomainTracking.Id.ToString();
}
}
else
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
Here is my Jquery request code:
function getSessionKey() {
var Domain = { 'Name': domainName };
var DomainTracking = { 'Domain': Domain, 'FormElements': getFormElements(), 'ClientLocation': clientLocation };
$.ajax({
url: 'http://api.testdomain.com:4646/api/' + apiKey,
type: 'GET',
cache: false,
timeout: 100000,
data: DomainTracking,
dataType: "jsonp",
error: function (xhr, status, error) {
},
success: function (data) {
sessionKey = data;
}
});
}
If I change the method name to GetStartTracking is receive a 500 error. If I leave the name StartTracking I get a 405 not allowed error. What do I need to do?
Upvotes: 1
Views: 1418
Reputation: 659
You may be missing the MediaTypeFormatter for jsonp.
I've created a sample project for this very thing and it's using the Telerik Kendo UI features but the cross-domain process is the same no matter what. You can download the sample application here: http://www.kendoui.com/code-library/mobile/listview.aspx.
Also you should either prefix the Api method with "Get" or add the [HttpGet] attribute to the method.
I hope this helps.
Upvotes: 0
Reputation: 173
Try using the "Get" as the name of your method. JSONP might not work with posts, so your data will all have to be in the url, I don't think you can use the data attribute of the ajax function.
This may help
public class TrackingController : ApiController {
... public string Get(string apiKey, string Domain, string FormElements, string ClientLocation) {
//do everything here
}
}
and the URL of the request should contain the name of your Controller and all information in the url. There might be other ways to do it, but this should work.
http://api.testdomain.com:4646/api/Tracking/?apiKey=something&Domain=abc&FormElements=1,2,3&ClientLocaiton=somewhere
Upvotes: 3