简体   繁体   English

如何在点网 c# 中击中 controller 之前读取原始 json 柱体?

[英]How to read the raw json post body before hitting the controller in dot net c#?

I need to implement a [HttpPost] web api with same route/uri, but more than 10 different combinations of parameters in json body.我需要实现一个[HttpPost] web api 具有相同的路由/uri,但在 json 正文中有超过 10 种不同的参数组合。 In which some parameters are null in some case but required in another case.其中一些参数在某些情况下是null但在另一种情况下是required的。 As I am migrating an already deployed project to dot net 6, I don't have the freedom to modify api routes.当我将一个已经部署的项目迁移到 dot net 6 时,我没有修改 api 路由的自由。

I have planned to execute this requirement by reading entire json raw body data in a model binder , deserialize it and setting it to different model classes before hitting the controller . I have planned to execute this requirement by reading entire json raw body data in a model binder , deserialize it and setting it to different model classes before hitting the controller . I assume that this method also helps me with model state validations , so that I need not perform any manual validations in controller or service .我认为这种方法还可以帮助我进行model state validations ,因此我不需要在controllerservice中执行任何手动验证。

Already existing code in java (Maven Web App Controller): java(Maven Web App Controller)中已经存在的代码:

@PostMapping(produces = HttpUtilities.APPLICATION_JSON_UTF8_VALUE, consumes = HttpUtilities.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<HashMap<String, Object>> postForApproving(@RequestBody HashMap<String, Object> record,
        HttpServletRequest request) {

    RequestStore requestStore = (RequestStore) request.getAttribute("requestStore");

    logger.info("postForApproving({})", requestStore.toString());

    AuthorizationService.checkApiRole(requestStore, "postForApproving_" + entity_name, "Staff-Management");

    HashMap<String, Object> respBody = getService().postForApproving(requestStore, record);

    return new ResponseEntity<HashMap<String, Object>>(respBody, HttpUtilities.getResponseHeaders(requestStore),
            HttpStatus.CREATED);
}

And in the service the 'action' parameter in the request record is checked in else-if conditions and corresponding repository method is called for each situation.并且在服务中,在 else-if 条件中检查请求记录中的“action”参数,并针对每种情况调用相应的存储库方法。

Custom Model Binder:定制 Model 粘合剂:

public class GetModelBindingContext : IModelBinder
{
    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        string json;
        using (var reader = new StreamReader(bindingContext.ActionContext.HttpContext.Request.Body, Encoding.UTF8))
            json = await reader.ReadToEndAsync();

        bindingContext.Result = ModelBindingResult.Success(json);
    }
}

Api Controller: Api Controller:

[ApiController]
public class ApproverDataController : ControllerBase
{
    private readonly IApproverDataService _myService;
    private readonly IModelBinder _modelBinder;

    public MyController(IMyService myService)
    {
        _myService = myService;
    }

    [Route("rest/prd/v1/post_data/body")]
    [HttpPost]
    public async Task<IActionResult> PostForAction([FromBody][ModelBinder(BinderType = typeof(GetModelBindingContext))] string json)
    {
        dynamic requestBody = JsonConvert.DeserializeObject(json);
        return Ok("Success!");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM