gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:26:09 25 4
gpt4 key购买 nike

我正在将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com