【问题标题】:Abort action execution in BindModel method在 BindModel 方法中中止操作执行
【发布时间】:2013-10-28 14:51:12
【问题描述】:

我已经在我的文件上传操作中实现了自定义模型绑定器。有时文件上传会被服务器丢弃,并且使用部分数据调用 BindModel 方法(ContentLenght 和 TotalBytes 在这里不匹配)。我想从自定义模型绑定器中止 Action 执行,该怎么做?

 public class OptionModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var optionModelName = GetOptionModelName(controllerContext);
            if (optionModelName != null) return null// !!!How to abort Action execution?!!! here

                Trace.TraceInformation(optionModelName);
                var model = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(optionModelName);
                bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());

            return base.BindModel(controllerContext, bindingContext);
        }

public class OptionModelBinderAttribute : CustomModelBinderAttribute
{

    public override IModelBinder GetBinder()
    {
        return new OptionModelBinder();
    }
}

[HttpPost]
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> clientUpload, [OptionModelBinder]IOptionViewModel formData)
{
}

【问题讨论】:

  • 为什么要中止模型绑定器中的动作执行?您可以简单地通知您的文件未正确上传:ModelState.AddModelError(errorMessage, new [] { fileName }); 在您的模型活页夹中,然后在您的操作中测试 ModelState.IsValid

标签: asp.net-mvc-3 model-binding


【解决方案1】:

这不是您想通过模型绑定执行的操作。
模型绑定不应控制逻辑行为。这没有意义。
我建议在控制器中,您会询问某些内容是否为 null 并将适当的结果返回给客户端。
让模型绑定做控制器的工作是不对的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-28
    • 2022-06-17
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    相关资源
    最近更新 更多