【问题标题】:.Net Core API Reject Incomplete JSON Request.Net Core API 拒绝不完整的 JSON 请求
【发布时间】:2020-08-19 07:33:51
【问题描述】:

如果正文的 JSON 不完整,我需要拒绝请求。

我有一个 .NetCore API,它有很多属性。该 API 会执行大量操作并且会收到大量请求,因此如果 JSON 不完整,请提前拒绝。

如果,我有下面的 AssignmentDetail 类,

public class AssignmentDetail
{
    public string Name { get; set; }
    public string Address { get; set; }
}

完整的 JSON 示例

{
     "Name":"dfsdfsdf", 
     "Address":"essdfsdfsd", 
}

不完整的 JSON 示例

{
     "Name":"dfsdfsdf" 
}

我有一些方法,但需要一些可以在启动时完成的东西,但只是为了那个动作。

  1. 为该 AssignmentDetail 模型使用自定义 Serializable (不想要这种方法)
  2. 创建一个函数来验证不完整的 JSON,例如 validateIncompleteJSON() (不想要这种方法)
  3. ConfigureServices(IServiceCollection 服务)中的某些内容,但仅用于该控制器操作

    [HttpPost]
    [Route("ProcessAssignment")]
    public async Task<AssignmentResponseModel> ProcessAssignment(AssignmentDetail model)
    {
        var response = new AssignmentResponseModel();
        try
        {
            //can call function here to check the incomlpete JSON 
            //validateIncompleteJSON();


            //var result = await _mediator.Send(queryDetails);
            //response = result.Response;
        }
        catch (Exception ex)
        {
            throw exception;
        }
        return response;
    }

我不想使用 Serializable 方式,因为该类太大并且必须处理所有属性。

【问题讨论】:

  • “不完整的 JSON”到底是什么意思?
  • @IanKemp 我已经编辑了问题来解释,我所说的不完整 JSON 是什么意思。谢谢。我希望,它解释了我的意思。
  • @Pratik Bhoir 只添加 [Required] 属性也是不可接受的吗?

标签: asp.net-mvc asp.net-core asp.net-web-api asp.net-core-mvc asp.net-core-webapi


【解决方案1】:

数据注释将必需属性添加到属性

型号代码

public class AssignmentDetail
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Address { get; set; }
}

控制器代码

    [HttpPost]
    [Route("/ProcessAssignment")]
    public IActionResult ProcessAssignment(AssignmentDetail model)
    {
        //var response = new AssignmentResponseModel();
        //try
        //{
        //    //can call function here to check the incomlpete JSON 
        //    //validateIncompleteJSON();


        //    //var result = await _mediator.Send(queryDetails);
        //    //response = result.Response;
        //}
        //catch (Exception ex)
        //{
        //    throw exception;
        //}
        //return response;

        if (ModelState.IsValid)
        {
            return Ok("Success");
        }
        return BadRequest();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 2022-01-01
    • 2019-12-06
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多