Microsoft.AspNetCore.Http.BadHttpRequestException:无法以JSON格式从请求正文中读取参数“xxx”

92dk7w1h  于 2023-10-21  发布在  其他
关注(0)|答案(1)|浏览(140)

我有一个React TypeScript应用程序,它调用了C#ASP.NET Core 7 Minimal API。
来自React应用程序的调用看起来像这样:
const resp = await Client.post('https://localhost:7196/institutions', JSON.stringify(doc));
Client的定义如下:

import axios from 'axios';
import { jsonrepair } from 'jsonrepair';

export class Client {
    static async post(url: string, jsonData: string) {
        const headers = {
            headers: { 'Content-Type': 'application/json' }
        };
        try {
            const response = await axios.post(url, jsonrepair(jsonData), headers );
            return response?.data;
        } catch (e) {
            return e.message;
        }
    }
}

我的最小API中的相关C#代码如下:

app.MapPost("/institutions", async ([FromBody]string instJson, InstitutionDb instDb, [FromHeader(Name = "Content-Type")] string contentType) =>
{
    var inst = JsonSerializer.Deserialize<Institution>(instJson);
    if (inst != null)
    {
        instDb.Institutions.Add(inst);
        await instDb.SaveChangesAsync();
        return Results.Created($"/institutions/{inst.Id}", inst);
    }
    return null;
});

然而,当执行它时-* 即使在验证传递的JSON是合法的 *(在使用TypeScript jsonrepair实用程序清理后),我收到以下错误:
Microsoft. AspNetCore. Http. BadHttpRequestException:无法以JSON格式从请求正文中读取参数"string instJson"。- > System. Text. Json. JsonException:JSON值无法转换为System.String。路径:$|行号:0| BytePositionInLine:1. -> System. InvalidOperationException:无法以字符串形式获取标记类型"StartObject"的值。在系统。发短信杰森ThrowHelper System.Text.Json.Utf8上的ThrowInvalidOperationException_ExpectedString(JsonTokenType tokenType)系统上的JsonReader.GetString()。发短信杰森序列化。JsonConverter 1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.Serialization.JsonConverter 1.ReadCore(Utf8JsonReader & reader,JsonSerializerOptions选项,ReadStack & state)-内部异常堆栈跟踪结束-在系统。发短信杰森ThrowHelper ReThrowWithPath(ReadStack & state,Utf8JsonReader & reader,Exception ex)at System.发短信杰森序列化。JsonConverter 1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.Serialization.JsonConverter 1.ReadCoreAsObject(Utf8JsonReader & reader,JsonSerializerOptions options,ReadStack & state)at System.发短信杰森JsonSerializer。系统上的ReadCore [TValue](Utf8JsonReader & reader,JsonTypeInfo jsonTypeInfo,ReadStack & state)。发短信杰森JsonSerializer。在System中继续初始化[TValue](ReadBufferState & bufferState,JsonReaderState & jsonReaderState,ReadStack & readStack,JsonTypeInfo jsonTypeInfo)。发短信杰森JsonSerializer。ReadFromStreamAsync [TValue](Stream utf8Json,JsonTypeInfo jsonTypeInfo,CancellationToken cancellationToken)at Microsoft. AspNetCore。HTTP。HttpRequestJsonExtensions。ReadFromJsonAsync(HttpRequest request,Type type,JsonSerializerOptions options,CancellationToken cancellationToken)at Microsoft. AspNetCore。HTTP。HttpRequestJsonExtensions。ReadFromJsonAsync(HttpRequest request,Type type,JsonSerializerOptions options,CancellationToken cancellationToken)at Microsoft. AspNetCore。HTTP。RequestDelegateFactory。g__TryReadBodyAsync| 90_0(HttpContext httpContext,Type bodyType,String parameterTypeName,String parameterName,Boolean allowEmptyRequestBody,Boolean throwOnBadRequest)-内部异常堆栈跟踪结束-位于Microsoft. AspNetCore. Http. RequestDelegateFactory. Log. InvalidJsonRequestBody(HttpContext httpContext,String parameterTypeName,String parameterName,Exception exception,Boolean shouldThrow)位于Microsoft. AspNetCore. Http. RequestDelegateFactory. g__TryReadBodyAsync| 90_0(HttpContext httpContext,Type bodyType,String parameterTypeName,String parameterName,Boolean allowEmptyRequestBody,Boolean throwOnBadRequest)at Microsoft.AspNetCore. Http.RequestDelegateFactory.<> c__DisplayClass90_2. d. MoveNext()-从上一位置开始的堆栈跟踪结束-at Microsoft. AspNetCore. Routing. EndpointMiddleware. g__AwaitRequestTask <b__2>6_0(Endpoint endpoint,Task requestTask,ILogger logger),位于Microsoft. AspNetCore. Diagnostics. HttpOperExceptionPageMiddlewareImpl. HttpContext上下文|
有趣的是,如果我在app.MapPost()上(或内部)调试并设置断点,断点不会被命中
为什么会这样?为什么端点失败,即使使用有效的JSON和正确设置的内容类型头?为什么我不能在C#代码中设置断点?
有什么建议吗?我已经在StackOverflow和其他地方广泛搜索了这个错误。其他人报告了这个错误,但我尝试过的解决方案都不适用于我。

oymdgrw7

oymdgrw71#

你把你的数据作为json发送,而不是作为字符串,所以改变了头

app.MapPost("/institutions", async ([FromBody]Institution inst)

并删除验证码

相关问题