我正在尝试在
ActionFilterAttribute
中获取请求正文。
JSON 值始终为“”。我正在使用 .NET7.0,我还将以下代码添加到
Program.cs
.Use(async (context, next) =>
{
try
{
context.Request.EnableBuffering();
await next();
}
catch (Exception e)
{
}
.
.
.
属性代码片段:
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var expectedModel = context.ActionArguments.Values.FirstOrDefault();
if (expectedModel == null)
{
context.Result = new BadRequestObjectResult("Model empty.");
return;
}
var requestBodyStream = new MemoryStream();
await context.HttpContext.Request.Body.CopyToAsync(requestBodyStream);
requestBodyStream.Seek(0, SeekOrigin.Begin);
var json = await new StreamReader(requestBodyStream).ReadToEndAsync();
}
我的控制器方法:
[HttpPost("scoring/add")]
[JsonModelValidationAttribute]
public async Task<IActionResult> AddScoringResult([FromBody] ScoreModel model)
{
//I am going to add logic.
}
我想获取请求正文并比较
ScoreModel
以检查是否有任何拼写错误的属性。如何从请求中获取正文?
课程和例子:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
public class JsonModelValidationAttribute : ActionFilterAttribute
{
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var expectedModel = context.ActionArguments.Values.FirstOrDefault();
if (expectedModel == null)
{
context.Result = new BadRequestObjectResult("Model empty.");
return;
}
var requestBodyStream = new MemoryStream();
await context.HttpContext.Request.Body.CopyToAsync(requestBodyStream);
requestBodyStream.Seek(0, SeekOrigin.Begin);
var json = await new StreamReader(requestBodyStream).ReadToEndAsync();
Console.WriteLine(json);
}
}
评分模型
using System;
using System.Collections.Generic;
using System.Security.Principal;
namespace Scoring.Data.Custom;
public class ScoreModel
{
public int Id { get; set; }
public int Score { get; set; }
public string Name { get; set; }
}
控制器
using Scoring.Data.Custom;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace Scoring.API.Custom;
[ApiController]
public class ScoringController : ControllerBase
{
public ScoringController()
{
}
[HttpPost("scoring/add")]
[JsonModelValidationAttribute]
public async Task<IActionResult> AddScoringResult([FromBody] ScoreModel model)
{
return Ok(model);
}
}