[英]How to read the raw json post body before hitting the controller in dot net c#?
我需要實現一個[HttpPost]
web api 具有相同的路由/uri,但在 json 正文中有超過 10 種不同的參數組合。 其中一些參數在某些情況下是null
但在另一種情況下是required
的。 當我將一個已經部署的項目遷移到 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
. 我認為這種方法還可以幫助我進行model state validations
,因此我不需要在controller
或service
中執行任何手動驗證。
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);
}
並且在服務中,在 else-if 條件中檢查請求記錄中的“action”參數,並針對每種情況調用相應的存儲庫方法。
定制 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:
[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.