【问题标题】:Middleware returns 400 error when JSON is deserializedJSON反序列化中间件返回400错误
【发布时间】:2022-12-25 22:51:42
【问题描述】:

我有一个非常简单的中间件:

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
  if(await CheckIfRequestIsAuthorize(context))
  {
   await next.Invoke(context);
  }
}

private async Task<bool> CheckIfRequestIsAuthorize(HttpContext context)
{
  Console.WriteLine("Inside method");
  string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();

  dynamic tmp = JsonConvert.DeserializeObject(requestBody);
  string sessionId = (string)tmp.sessionId;

  if(sessionId == "string")
  {
    return true;
  } else
  {
    return false;
  }
}

// this is my controller and class

public class MyOwnRequest
{
  public string SessionId { get; set; }
  public string SpecialKey { get; set; }
}

[HttpPost]
public async Task<IActionResult> PostMethod([FromBody] MyOwnRequest myOwnRequest)
{
  return Ok("It's okey");
}

当我发出请求时,出现错误: “输入不包含任何 JSON 标记。当 isFinalBlock 为真时,预期输入以有效的 JSON 标记开头。

Path: $ | LineNumber: 0 | BytePositionInLine: 0.

我发现问题出在这部分代码上,因为当我们这样做时:

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
  string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
  await next.Invoke(context);
}

这也引起了一个问题,也许有人有类似的问题?

身体:

{
  "sessionId": "string",
  "specialKey": "string"
}

编辑:

我发现我需要启用双重读取请求的正文。但我为什么要这样做?当一个方法在next.invoke之前时,它应该只被调用一次。

【问题讨论】:

  • 你没有在读取流后调整指针的位置

标签: asp.net-core json-deserialization asp.net-core-middleware


【解决方案1】:

我尝试如下:

app.Use(async (context, next) =>
{
  var request = context.Request;
  request.EnableBuffering();
  var stream = request.Body;
  long? length = request.ContentLength;
  if(length!=null&length>0)
  {
    StreamReader reader = new StreamReader(stream);
    var jsonstr = reader.ReadToEndAsync().Result;
    dynamic tmp =JsonConvert.DeserializeObject(jsonstr);
    string sessionId = (string)tmp.SessionId;
  }

 context.Request.Body.Position = 0;
 await next.Invoke();
});

结果:

如果不调整指针的位置:

【讨论】:

    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多