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

标签 c# console-application asp.net-web-api self-hosting

我使用了这篇博文中描述的 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/

相关文章:

c# - 关联列表<T>。删除到 C# 中的事件?

c# - 对数据库的更改已成功提交...ObjectContext 可能处于不一致状态

c# - 从通用接口(interface)继承

c# - 获取 "The entity type <model> is not part of the model for the current context."

c# - 如何在控制台应用程序中隐藏输出(不是窗口)?

asp.net-web-api - 将WCF数据服务OData提供程序转换为Web API的最简单方法是什么?

javascript - Web API Controller 不尊重 CORS 来源

java - 如何将 GZIP 内容编码应用于 HTTP 文件上传 multipart/form-data POST

c++ - 在控制台应用程序和 Windows 窗体之间共享数据

asp.net - MassTransit 得到消费者的回应