在Asp.net Core Controller中,可能需要进行自定义ModelBinding以处理复杂的数据类型。在这种情况下,可能会遇到以下几个问题:
下面给出针对每个问题的解决方案:
在Asp.net Core中,有多种ModelBindingProvider,它们按照优先级逐个尝试将请求数据绑定到控制器的参数中。如果你想要让自己的ModelBindingProvider优先级更高,可以在Startup中配置Order属性。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(options =>
{
options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(
_ => "The field is required.");
// Add custom binding source
options.ModelBindingProviders.Insert(0, new MyCustomBindingProvider());
});
}
有时候,需要对特定类型的数据进行自定义绑定处理,这时候可以实现IModelBinder接口,并重写它的BindModelAsync方法。下面是一个简单的示例,它将请求体中的JSON数据绑定到Person类的实例中。
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class JsonBodyModelBinder : IModelBinder
{
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
var content = await new StreamReader(bindingContext.HttpContext.Request.Body).ReadToEndAsync();
var person = JsonConvert.DeserializeObject(content);
bindingContext.Result = ModelBindingResult.Success(person);
}
}
public class HomeController: Controller
{
public IActionResult ProcessJsonBody([ModelBinder(BinderType = typeof(JsonBodyModelBinder))] Person person)
{
return Json(person);
}
}