从自托管的WEB API控制台应用程序返回jsonp

我使用了这篇博客文章中描述的jsonp格式化程序: http : //www.west-wind.com/weblog/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API

有没有人尝试将格式化程序与自托管控制台应用程序一起使用?

我在常规的MVC 4项目中尝试过格式化程序,它立即起作用。 但是,我想在自托管控制台应用程序中使用它,我在使用它时遇到了很多麻烦。

我已注册格式化程序,并validation它已添加:

var config = new HttpSelfHostConfiguration(serviceUrl); config.Formatters.Insert(0, new JsonpMediaTypeFormatter()); 

我已经validation在使用以下代码发出请求时正在调用格式化程序:

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

我已经检查了Fiddler,我得到的回答是:

 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. 

如果有人能够了解正在发生的事情,我将非常感激!

谢谢,

弗朗西斯

我怀疑Disposing StreamWriter会导致问题。 尝试调整WriteToStreamAsync方法:

 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); }