c# - 替换 ASP.net MVC 核心中的 DefaultModelBinder

标签 c# asp.net-mvc nhibernate asp.net-core-mvc

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

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

提前致谢!

最佳答案

你可以这样做:

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; }
    }
}

关于c# - 替换 ASP.net MVC 核心中的 DefaultModelBinder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50893324/

相关文章:

c# - 为C#控制台应用程序添加背景音频

c# - PL/SQL 问题返回序列标量值

c# - MVC View 中的安全性

基于 NHibernate 的全文搜索

c# - 静态变量的初始化顺序不明确

c# - 将 IEnumerable 强制转换为 IList<TResult> 是否会枚举序列,为什么首选这种方式?

c# - INotifyPropertyChanged,这在 MVC 等 Web 应用程序中如何工作或如何工作?

javascript - 我如何在没有 ajax 调用的情况下在 window.location 中传递数组

c# - session 关闭后加载子对象

NHibernate 与 SQL Server 分页