【问题标题】:get 400 error when using API POST to controller in React在 React 中使用 API POST 到控制器时出现 400 错误
【发布时间】:2021-07-10 20:54:31
【问题描述】:

我正在使用 .NetCore 5 Entity Framework 来搜索我的数据。

当我发布数据时,我从 api 收到 400 错误 我的控制器:

public IActionResult Search( [FromBody]string data)

我的反应:


handleSubmit(event){
    event.preventDefault();
        const data = JSON.stringify({
            searchTitle: this.state.searchTitle,
            boolTitle: this.state.boolTitle,
            boolSubject:this.state.boolSubject,
            searchElement:this.state.searchElement,
            refrence:this.state.refrence,
            maker:this.state.maker,
            subject:this.state.subject,
            startTimeArea:this.state.startTimeArea,
            endTimeArea:this.state.endTimeArea,
            type:this.state.type,
            isAvtive:this.state.isAvtive,
            enacmentTime:this.state.enacmentTime
        });
    const headers = {
        'Content-Type': 'application/json' ,
        'Accept':'application/json'
      }
    axios.post('/api/searchPost/search',data,{
        headers: headers
      }).
      then(result => console.log(result)).
      catch((error) => {
        console.log(error);
    });
}

我尝试将 [fromBody] 更改为 [fromForm] 400 错误已修复,但控制器字符串中的接收值为 null

【问题讨论】:

标签: c# reactjs asp.net-core


【解决方案1】:

当我发布数据时,我从 api myController 收到 400 错误:

公共 IActionResult 搜索([FromBody]字符串数据)

要使用数据发出 HTTP 请求并使其绑定到字符串类型的操作参数,您需要实现并使用自定义纯文本输入格式化程序,如下所示。

public class TextPlainInputFormatter : TextInputFormatter
{
    public TextPlainInputFormatter()
    {
        SupportedMediaTypes.Add("text/plain");
        SupportedEncodings.Add(UTF8EncodingWithoutBOM);
        SupportedEncodings.Add(UTF16EncodingLittleEndian);
    }

    protected override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
    {
        string data = null;
        using (var streamReader = new StreamReader(context.HttpContext.Request.Body))
        {
            data = await streamReader.ReadToEndAsync();
        }
        return InputFormatterResult.Success(data);
    }
} 

添加自定义格式化程序支持

public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddControllers(opt => opt.InputFormatters.Insert(0, new TextPlainInputFormatter()));

在前端更新请求标头

const headers = {
    'Content-Type': 'text/plain',
    'Accept': 'application/json'
}

axios.post('/api/searchPost/search', data, {
    headers: headers
}).
    then(result => console.log(result)).
    catch((error) => {
        console.log(error);
    });

【讨论】:

  • 我相信这是一个 X/Y 问题。 OP 认为他需要一个带有问题中签名的控制器方法,而他确实需要一个接受 DTO 的控制器方法。 BR
猜你喜欢
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多