WebApi:ID 之间不匹配

鉴于以下路线


/api/Person/15

我们用 body 对这条路由执行 PUT 操作:


{

    id: 8,

    name: 'Joosh'

}

路线段值为 ,15但[FromBody]id 为8。


现在我们的控制器中有如下内容:


public Model Put(string id, [FromBody] Model model)

{

     if (id != model.Id)

         throw new Exception("Id mismatch!");


     // ... Do normal stuff

}

是否有一个“默认”或干燥的方法来执行此操作,而不假设它总是像参数 ID 和 Model.Id 属性一样简单?


临摹微笑
浏览 159回答 3
3回答

侃侃无极

您可以通过自定义模型验证来实现[HttpPut("api/Person/{id}")]public IActionResult Put(string id, [FromBody]Person person){    // ... Do normal stuff    return Ok();}public class Person{    [ValidateId]    public string Id { get; set; }    public string Name { get; set; }}public sealed class ValidateId : ValidationAttribute{    protected override ValidationResult IsValid(object id, ValidationContext validationContext)    {        var httpContextAccessor = (IHttpContextAccessor)validationContext.GetService(typeof(IHttpContextAccessor));        var routeData = httpContextAccessor.HttpContext.GetRouteData();        var idFromUrl = routeData.Values["id"];        if (id.Equals(idFromUrl))        {            return ValidationResult.Success;        }        else        {            return new ValidationResult("Id mismatch!");        }    }}// In the Startup class add the IHttpContextAccessorpublic void ConfigureServices(IServiceCollection services){    // ...    services.AddHttpContextAccessor();    // ...}

梦里花落0921

是否有一个“默认”或干燥的方法来执行此操作,而不假设它总是像参数 ID 和 Model.Id 属性一样简单?自定义验证逻辑可以在 ActionFilter 中实现。由于 ActionFilter 是在操作执行中的模型绑定之后进行处理的,因此可以在 ActionFilter 中使用模型和操作参数,而无需从请求正文或 URL 中读取。您可以参考下面的工作演示:自定义验证过滤器public class ValidationFilter: ActionFilterAttribute{&nbsp;private readonly ILogger _logger;public ValidationFilter(ILoggerFactory loggerFactory){&nbsp; &nbsp; _logger = loggerFactory.CreateLogger("ValidatePayloadTypeFilter");}public override void OnActionExecuting(ActionExecutingContext context){&nbsp; &nbsp; var carDto = context.ActionArguments["car"] as Car;&nbsp; &nbsp; var id = context.ActionArguments["id"];&nbsp; &nbsp; if (Convert.ToInt32(id)!=carDto.Id)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; context.HttpContext.Response.StatusCode = 400;&nbsp; &nbsp; &nbsp; &nbsp; context.Result = new ContentResult()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Content = "Id mismatch!"&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; base.OnActionExecuting(context);&nbsp;}}在ConfigureServices方法中注册此操作过滤器services.AddScoped<ValidationFilter>();将此操作过滤器称为服务public class Car{&nbsp; &nbsp;public int Id { get; set; }&nbsp; &nbsp;public string CarName { get; set; }}[ServiceFilter(typeof(ValidationFilter))][HttpPut("{id}")]public Car Put(int id, [FromBody] Car car){&nbsp;// the stuff you want}

素胚勾勒不出你

您可以创建自己的 CustomValidation 并比较 id 和 model.id 的值。
打开App,查看更多内容
随时随地看视频慕课网APP