简体   繁体   English

如何处理 AspNet Core 自定义 ModelBinder 中的错误

[英]How to handle errors in AspNet Core Custom ModelBinder

I´m trying to create a custom model binder that cancels the request when the given data is invalid.我正在尝试创建一个自定义 model 活页夹,当给定数据无效时取消请求。

public sealed class DeploymentIdModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        string modelName = bindingContext.ModelName;

        string? value = bindingContext
            .ValueProvider
            .GetValue(modelName)
            .FirstValue;

        if (value is null)
            return Task.CompletedTask;

        if(DeploymentId.TryParse(value, out var id))
        {
            bindingContext.Result = ModelBindingResult.Success(id);
        }
        else
        {
            bindingContext.ModelState.TryAddModelError(modelName, $"{value} is not a valid {nameof(DeploymentId)}.");
            bindingContext.Result = ModelBindingResult.Failed();
        }
        return Task.CompletedTask;
    }
}

[HttpGet]
[Route("download/{deploymentId}")]
public async Task<IActionResult> DownloadDeployment(DeploymentId deploymentId)
{
    ...
}

I expected to not hit the endpoint if I pass in an invalid DeploymentId.如果我传入无效的 DeploymentId,我希望不会到达端点。 But instead the method gets called with deploymentId = null .但相反,该方法被调用deploymentId = null

Do I have a wrong expectation/Do I missunderstand how the binders should work?我是否有错误的期望/我是否误解了活页夹应该如何工作? And if, how would I do it the wright way?如果,我将如何以正确的方式做到这一点?

Thanks for your answers!感谢您的回答!

You can refer to this document .你可以参考这个文件 And use url like: https://localhost:7273/authors/index?id=1并使用 url 像:https://localhost:7273/authors/index?id=1

result:结果:

在此处输入图像描述

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

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