代码之家  ›  专栏  ›  技术社区  ›  user875234

wait actioncontext.request.content.readasstringasync()返回空字符串

  •  0
  • user875234  · 技术社区  · 7 年前

    首先

    var myString = await actionContext.Request.Content.ReadAsStringAsync();
    

    应该一直工作。但事实并非如此。我们开始:

    飞机控制器.cs

    [ValidateAirplane]
    [HydrateAirplane]
    public class AirplaneController : ApiController
    

    validateairplane.cs(请参见神奇的魔力线)

    public class ValidateAirplaneAttribute : FilterAttribute, IAuthorizationFilterpublic class ValidateAirplaneAttribute : FilterAttribute, IAuthorizationFilter
    ...
    public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        var json = await actionContext.Request.Content.ReadAsStringAsync(); // <-- amazing magic line
        return await continuation();
    }
    

    水合物飞机.cs

    public class HydrateAirplaneAttribute : FilterAttribute, IActionFilter
    ...
    public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        var json = await actionContext.Request.Content.ReadAsStringAsync();
        return await continuation();
    }
    

    如果我评论 amazing magic line 然后 json 在里面 ExecuteAuthorizationFilterAsync 作为空字符串返回。但是如果我不评论 神奇线条 我得到了JSON(来自客户的飞机JSON)。

    起初我认为这可能是一个时间问题,所以我试着做了一个 await Task.Delay(5000) 在里面 HydrateAirplane.cs 在尝试读取JSON之前,它没有任何效果。

    知道是什么问题吗?

    0 回复  |  直到 7 年前
        1
  •  0
  •   user875234    7 年前

    这与其说是一个答案,倒不如说是一项工作。如果你有更好的答案,请分享。我注意到有一个 ReadAsStreamAsync 我能让它发挥作用。也许这是webapi中的一个bug?我找不到密码 github 所以我不确定。我的工作是使用这个扩展方法而不是 ReadAsStringAsync :

    public async static Task<string> GetRequestBody(this HttpActionContext actionContext)
    {
        var bodyStream = await actionContext.Request.Content.ReadAsStreamAsync();
        bodyStream.Position = 0;
    
        var bytes = new byte[bodyStream.Length];
        await bodyStream.ReadAsync(bytes, 0, bytes.Length);
    
        bodyStream.Position = 0; // <-- i don't know why but this line is important. it doesn't work on subsequent calls without this. ...to be clear, it absolutely should work. i consider this to be a WebAPI work around. that is, i should not have to ever even think about this.
    
        return Encoding.ASCII.GetString(bytes);
    }
    

    之所以没有用using包装,是因为它是用using包装的,但是WebAPI开始抛出流是不可读的错误,我猜这意味着它们使用的是内部返回给您的完全相同的流。

    推荐文章