关于ASP.NET.CORE中的Failed to read parameter "string param" from the request body as JSON的处理

发布时间 2023-06-19 12:49:40作者: mikodopants

先上报错信息

Microsoft.AspNetCore.Http.BadHttpRequestException: Failed to read parameter "string param" from the request body as JSON.
 ---> System.Text.Json.JsonException: 's' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
 ---> System.Text.Json.JsonReaderException: 's' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
   at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
...

 

对应的Post请求信息(来自vs2022的.http文件发起的请求),请求的body为下图的string

可以通过该链接了解到 .http文件  使用 Visual Studio 2022 中的 .http 文件

###Not Correct Case 1
Post {{WebAppTest_FromBody_HostAddress}}/PostStringAtBody
Content-Type:application/json

string

 

终结点PostStringAtBody

app.MapPost("/PostStringAtBody", (HttpContext httpContext, [FromBody]string param) => 
{
    return param;
});

注:string param前序添加[FromBody]否则认为param来自QueryString。

具体解决方案

按照报错信息,以JSON格式读取body的参数时失败。传入的参数string并不是标准的JSON。给string加上双引号即可正确调用。

Post {{WebAppTest_FromBody_HostAddress}}/PostStringAtBody
Content-Type:application/json

"string"
-------------------------------------------------------------------------
响应时间: 64 ms
状态代码: OK (200)
Transfer-Encoding: chunked
Date: Wed, 14 Jun 2023 18:55:58 GMT
Server: Kestrel

Content-Type: text/plain; charset=utf-8
Content-Length: 6

------------------------------------------------
内容:
string

 

拓展

那么,如果入参本来就不是标准JSON或者body里的JSON有多种可能时(比如有时候是school,有时是student,还可能如本例的string),那么,你可能选择一下其中一种处理方式:

1)通过中间件Middleware或者ActionFilter形式提前对body进行一定的处理.

2)在请求到达Controller时再对Request.Body进行处理

 
[HttpPost]
public async Task<string> Test() { using (StreamReader sr = new StreamReader(this.HttpContext.Request.Body, leaveOpen: true)) { return await sr.ReadToEndAsync(); } }