1

ASP.NET 5 RC1 でカスタム モデル バインダーを使用して解析しようとすると、アクションを呼び出すときにNullReferenceExceptionスローされます。Microsoft.AspNet.Mvc.ModelBinding.CompositeModelBinder

スタートアップでのモデル バインディング:

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. Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNet.Mvc.Controllers.DefaultControllerActionArgumentBinder.d__6.MoveNext() --- 例外がスローされた前の場所からのスタック トレースの終わり --- System.Runtime.CompilerServices でMicrosoft.AspNet.Mvc.Controllers の System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(タスク タスク) での .TaskAwaiter.ThrowForNonSuccess(タスク タスク)。

4

1 に答える 1

1

inメソッド呼び出しに変更return nullしてください。return Task.FromResult(ModelBindingResult.NoResult);BindModelAsync

64行のCompositeModelBinder.csで、フレームワークがnullであるvar result = await binder.BindModelAsync(bindingContext);と待機するとエラーが発生しますTask

于 2015-12-12T13:14:00.913 に答える