Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return jsonp from self hosted WEB API Console app

I've use the jsonp formatter described in this blog post: http://www.west-wind.com/weblog/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API

Has anybody tried using the formatter with a self hosted console application?

I've tried the formatter in a regular MVC 4 project, and it worked immediately. However, I would like to use it in a self hosted console application, and I've had a lot of trouble getting it to work.

I've registered the formatter, and verified that it is added:

var config = new HttpSelfHostConfiguration(serviceUrl);

config.Formatters.Insert(0, new JsonpMediaTypeFormatter());

I have verified that the formatter is being called when I make a request with the following code:

$("#TestButton").click(function () {         
    $.ajax({
        url: 'http://localhost:8082/Api/Test',
        type: 'GET',
        dataType: 'jsonp',
        success: function(data) {
            alert(data.TestProperty);
        }
    }); 
})

I've checked in Fiddler, and the response I get is:

HTTP/1.1 504 Fiddler - Receive Failure
Content-Type: text/html; charset=UTF-8
Connection: close
Timestamp: 09:30:51.813

[Fiddler] ReadResponse() failed: The server did not return a response for this request.

I'd be really grateful if anybody can shed some light on what is going on!

Thanks,

Francis

like image 743
Francis Avatar asked Feb 17 '26 14:02

Francis


1 Answers

I suspect that Disposing the StreamWriter causes issues here. Try adapting the WriteToStreamAsync method:

public override Task WriteToStreamAsync(
    Type type, 
    object value,
    Stream stream,
    HttpContent content,
    TransportContext transportContext
)
{
    if (string.IsNullOrEmpty(JsonpCallbackFunction))
    {
        return base.WriteToStreamAsync(type, value, stream, content, transportContext);
    }

    // write the JSONP pre-amble
    var preamble = Encoding.ASCII.GetBytes(JsonpCallbackFunction + "(");
    stream.Write(preamble, 0, preamble.Length);

    return base.WriteToStreamAsync(type, value, stream, content, transportContext).ContinueWith((innerTask, state) =>
    {
        if (innerTask.Status == TaskStatus.RanToCompletion)
        {
            // write the JSONP suffix
            var responseStream = (Stream)state;
            var suffix = Encoding.ASCII.GetBytes(")");
            responseStream.Write(suffix, 0, suffix.Length);
        }
    }, stream, TaskContinuationOptions.ExecuteSynchronously);
}
like image 189
Darin Dimitrov Avatar answered Feb 20 '26 04:02

Darin Dimitrov