I am working on creating a new set of services in ASP.MVC MVC 4 using the Web API. So far, it's great. I have created the service and gotten it to work, and now I am trying to consume it using JQuery. I can get back the JSON string using Fiddler, and it seems to be ok, but because the service exists on a separate site, trying to call it with JQuery errors with the "Not Allowed". So, this is clearly a case where I need to use JSONP.
I know that the Web API is new, but I'm hoping someone out there can help me.
How do I make a call to a Web API method using JSONP?
Here's an updated version with several improvements, which works with the RTM version of Web APIs.
Accept-Encoding
headers. Thenew StreamWriter()
in the previous examples would simply use UTF-8. The call tobase.WriteToStreamAsync
may use a different encoding, resulting in corrupted output.application/javascript
Content-Type
header; the previous example would output JSONP, but with theapplication/json
header. This work is done in the nestedMapping
class (cf. Best content type to serve JSONP?)StreamWriter
and directly gets the bytes and writes them to the output stream.ContinueWith
mechanism to chain several tasks together.Code:
I'm aware of the "hackiness" of the
Func<string>
parameter in the inner class constructor, but it was the fastest way to get around the problem it solves -- since C# only has static inner classes, it can't see theCallbackQueryParameter
property. Passing theFunc
in binds the property in the lambda, soMapping
will be able to access it later on inTryMatchMediaType
. If you have a more elegant way, please comment!Here is an updated version of the JsonpMediaTypeFormatter for use with WebAPI RC:
Certainly Brian's answer is the correct one, however if you already are using the Json.Net formatter, which gives you pretty json dates and faster serialization, then you can't just add a second formatter for jsonp, you have to combine the two. It is a good idea to use it anyway, as Scott Hanselman has said that the release of ASP.NET Web API is going to use the Json.Net serializer by default.
Rick Strahl's implementation worked best for me with RC.
For those of you who are using the HttpSelfHostServer this section of code will fail on HttpContext.Current, since it doesn't exist on the self host server.
However you can intercept the self host "context" via this override.
The request.Method will give you "GET", "POST", etc. and the GetQueryNameValuePairs can retrieve the ?callback parameter. Thus my revised code looks like:
Hope this helps some of you. This way you don't necessarily need a HttpContext shim.
C.
johperl, Thomas. The answer given by Peter Moberg above should be correct for the RC version as the JsonMediaTypeFormatter that he inherits from uses the NewtonSoft Json serializer already, and so what he has should work with out any changes.
However, why on earth are people still using out parameters, when you could just do the following