从自我托管的Web API控制台应用程序返回的JSONP(Return jsonp from sel

2019-09-22 06:33发布

我已经使用这个博客帖子描述的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);
        }
    }); 
})

我在提琴手检查,我得到的回应是:

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.

我会非常感激,如果任何人都可以阐明这是怎么回事一些轻!

谢谢,

弗朗西斯

Answer 1:

我怀疑是报废后的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);
}


文章来源: Return jsonp from self hosted WEB API Console app