编程语言
首页 > 编程语言> > c#-从自托管的WEB API控制台应用返回jsonp

c#-从自托管的WEB API控制台应用返回jsonp

作者:互联网

我使用了此博客文章中描述的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.

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

谢谢,

弗朗西斯

解决方法:

我怀疑处理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);
}

标签:self-hosting,asp-net-web-api,console-application,c
来源: https://codeday.me/bug/20191031/1979327.html