替换 ASP.net MVC 核心中的 DefaultModelBinder [英] Replacing DefaultModelBinder in ASP.net MVC core

查看:23
本文介绍了替换 ASP.net MVC 核心中的 DefaultModelBinder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个 MVC 5 项目转换为核心.我目前有一个自定义模型绑定器,用作我的 nhibernate 实体模型绑定器.我可以选择通过从数据库中提取实体,然后调用基本 DefaultModelBinder 将修改后的数据从请求绑定到实体来获取和绑定.

I am converting an MVC 5 project over to core. I currently have a custom model binder that I use as my nhibernate entity model binder. I have the option to fetch and bind by fetching the entity out of the database then calling the base DefaultModelBinder to bind modified data from the request into the entity.

现在我正在尝试实现 IModelBinder...我可以很好地获取实体.但是,当我不再有可调用的基本 DefaultModelBinder 时,如何调用默认模型绑定器"以绑定其余的表单数据?

Now I am trying to implement IModelBinder... I can fetch the entity just fine. But how do I call the "default model binder" in order to bind the rest of the form data when I no longer have a base DefaultModelBinder to call?

提前致谢!

推荐答案

你可以这样做:

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace Media.Onsite.Api.Middleware.ModelBindings
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                // add the custom binder at the top of the collection
                options.ModelBinderProviders.Insert(0, new MyCustomModelBinderProvider());
            });
        }
    }

    public class MyCustomModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context.Metadata.ModelType == typeof(MyType))
            {
                return new BinderTypeModelBinder(typeof(MyCustomModelBinder));
            }

            return null;
        }
    }

    public class MyCustomModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            if (bindingContext.ModelType != typeof(MyType))
            {
                return Task.CompletedTask;
            }

            string modelName = string.IsNullOrEmpty(bindingContext.BinderModelName)
                ? bindingContext.ModelName
                : bindingContext.BinderModelName;

            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
            if (valueProviderResult == ValueProviderResult.None)
            {
                return Task.CompletedTask;
            }

            bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);

            string valueToBind = valueProviderResult.FirstValue;

            if (valueToBind == null /* or not valid somehow*/)
            {
                return Task.CompletedTask;
            }

            MyType value = ParseMyTypeFromJsonString(valueToBind);

            bindingContext.Result = ModelBindingResult.Success(value);

            return Task.CompletedTask;
        }

        private MyType ParseMyTypeFromJsonString(string valueToParse)
        {
            return new MyType
            {
                // Parse JSON from 'valueToParse' and apply your magic here
            };
        }
    }

    public class MyType
    {
        // Your props here
    }

    public class MyRequestType
    {
        [JsonConverter(typeof(UniversalDateTimeConverter))]
        public MyType PropName { get; set; }

        public string OtherProp { get; set; }
    }
}

这篇关于替换 ASP.net MVC 核心中的 DefaultModelBinder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆