简体   繁体   English

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

[英]HttpClient.PostAsync return System.IO.Stream as property

I have some legacy code that I'm trying to work with and need to return an existing object that contains a Stream from an ApiController 我有一些遗留代码,我正在尝试使用它们,并且需要从ApiController返回包含Stream的现有对象

public class LegacyObject
{
    public bool Result { get; set; }
    public Stream Stream { get; set; }       
}

API Code 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
    }
}

My call to the Api is 我打给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;                                        

}

I get a 500 Internal Server Error on the PostAsync when my LegacyObject.Stream has content. 当我的LegacyObject.Stream包含内容时,我在PostAsync上收到500 Internal Server Error It works when the stream content is null. 当流内容为null时,它起作用。 I'm working locally on my development PC and web server for the API is IIS Express. 我在开发PC和Web服务器上本地工作,因为IIS Express是API。

Any advice would be appreciated. 任何意见,将不胜感激。

So in order to get more detail on the 500 Internal Server Error, I added this to my projects WebApiConfig Register 因此,为了获得有关500 Internal Server Error的更多详细信息,我将此添加到了项目WebApiConfig Register中

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

With this class 上这堂课

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

The log variable now gives me the detail I need to debug 现在,log变量为我提供了我需要调试的详细信息

FYI - The error was a read timeout on my Stream 仅供参考-错误是我的流上的读取超时

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

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