简体   繁体   English

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

[英]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 我使用了这篇博文中描述的jsonp格式化程序: 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. 我在常规MVC 4项目中尝试过格式化程序,它立即起作用。 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: 我已经检查了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.

I'd be really grateful if anybody can shed some light on what is going on! 如果有人能够了解正在发生的事情,我将非常感激!

Thanks, 谢谢,

Francis 弗朗西斯

I suspect that Disposing the StreamWriter causes issues here. 我怀疑Disposing StreamWriter会导致问题。 Try adapting the WriteToStreamAsync method: 尝试调整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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM