1

当尝试在 ASP.NET 5 RC1 中使用自定义模型绑定器进行解析时,我NullReferenceExceptionMicrosoft.AspNet.Mvc.ModelBinding.CompositeModelBinder调用操作时遇到了问题。

Startup 中的模型绑定:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.ModelBinders.Insert(0, new MyCustomModelBinder());
}

自定义模型绑定器:

public class MyCustomModelBinder : IModelBinder
{
    public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(MyCustomClass) && bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null)
        {
            MyCustomClass model;
            var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).FirstValue as string;

            if (MyCustomClass.TryParse(val, out model))
            {
                return Task.FromResult(ModelBindingResult.Success(bindingContext.ModelName, model));
            }
        }

        return null;
    }
}

控制器动作:

[HttpGet]
public IActionResult GetSomething([ModelBinder(BinderType = typeof(MyCustomModelBinder))]MyCustomClass key)
{
    return Json("Success!");
}

例外:

System.NullReferenceException:对象引用未设置为对象的实例。在 Microsoft.AspNet.Mvc.ModelBinding.CompositeModelBinder.d__5.MoveNext() --- 从先前抛出异常的位置结束堆栈跟踪--- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System. Microsoft.AspNet.Mvc.Controllers.DefaultControllerActionArgumentBinder.d__6.MoveNext() 处的 Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) --- 在 System.Runtime.CompilerServices 处从先前引发异常的位置结束堆栈跟踪.TaskAwaiter.ThrowForNonSuccess(任务任务)在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在 Microsoft.AspNet.Mvc.Controllers。

4

1 回答 1

1

请更改return nullreturn Task.FromResult(ModelBindingResult.NoResult);inBindModelAsync方法调用。

CompositeModelBinder.csvar result = await binder.BindModelAsync(bindingContext);中,当框架等待Task为空时发生64 行错误

于 2015-12-12T13:14:00.913 回答