HttpClient.PostAsync将System.IO.Stream作为属性返回

时间:2018-06-03 21:10:54

标签: c# asp.net-web-api

我有一些我尝试使用的遗留代码,需要从 ApiController

返回包含 Stream 的现有对象
public class LegacyObject
{
    public bool Result { get; set; }
    public Stream Stream { get; set; }       
}

API代码

public class BindJson : System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        string rawRequest;
        using (var stream = new StreamReader(actionContext.Request.Content.ReadAsStreamAsync().Result))
        {
            stream.BaseStream.Position = 0;
            rawRequest = stream.ReadToEnd();
        }
        rawRequest = rawRequest.ToString();
        var obj  = JsonConvert.DeserializeObject<LegacyParameters>(rawRequest.ToString());
        actionContext.ActionArguments["parameter"] = obj;                
     }

}
public class ReportsController : ApiController
{
    [BindJson]
    [HttpPost]
    public LegacyObject ReturnReport([FromBody]LegacyParameters parameter)
    {           
        LegacyObject r = LegacyClass.GetReportStream(parameters);
        return r; //Object properties are correctly set and no errors at this point
    }
}

我对Api的呼吁是

using (var httpClient = new System.Net.Http.HttpClient())
{
    httpClient.BaseAddress = new Uri("http://myserver/");

    string contents = JsonConvert.SerializeObject(paramList);

    var response = httpClient.PostAsync("/api/ReturnReport", new StringContent(contents, Encoding.UTF8, "application/json")).Result;                                        

}

当我的LegacyObject.Stream包含内容时,PostAsync上出现 500内部服务器错误。它在流内容为空时有效。我在我的开发PC本地工作,而API的Web服务器是IIS Express。

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

因此,为了获得有关500内部服务器错误的更多详细信息,我将其添加到我的项目中 WebApiConfig 注册

config.Services.Replace(typeof(IExceptionLogger), new UnhandledExceptionLogger());

使用此课程

public class UnhandledExceptionLogger : ExceptionLogger
{
    public override void Log(ExceptionLoggerContext context)
    {
        var log = context.Exception.ToString();
        //Write the exception to your logs
    }
}

现在,日志变量为我提供了调试所需的详细信息

仅供参考 - 错误是我的Stream上的读取超时