我使用了这篇博文中描述的 jsonp 格式化程序:http://www.west-wind.com/weblog/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API
有人试过将格式化程序与自托管控制台应用程序一起使用吗?
我已经在常规 MVC 4 项目中尝试过格式化程序,它立即起作用。但是,我想在自托管控制台应用程序中使用它,但我在让它工作时遇到了很多麻烦。
我已经注册了格式化程序,并验证它已被添加:
var config = new HttpSelfHostConfiguration(serviceUrl);
config.Formatters.Insert(0, new JsonpMediaTypeFormatter());
当我使用以下代码发出请求时,我已验证正在调用格式化程序:
$("#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 the 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);
}
关于c# - 从自托管的 WEB API 控制台应用程序返回 jsonp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12347461/