sre*_*moh 3 asp.net-mvc asp.net-web-api asp.net-mvc-5 asp.net-web-api2
我已经为我的WebApi项目实现了自定义模型绑定器
using WebApi.Controllers;
using System.Web.Http.ModelBinding;
using System.Web.Http.Controllers;
namespace WebApi.Models
{
public class ModelBaseBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if ((bindingContext.Model is MyModel))
{
//my code here
controller.InitModel(model);
return true;
}
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但由于某些原因在Global.asax.cs排队GlobalConfiguration.Configure(WebApiConfig.Register);,我得到一个错误:The type does not implement the IModelBinder interface. Parameter name: binderType.
我Global.asax.cs看起来像那样:
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutoMapperConfiguration.Configure();
GlobalConfiguration.Configuration.BindParameter(typeof(ModelBase), new ModelBaseBinder());
FluentValidationModelValidatorProvider.Configure(GlobalConfiguration.Configuration);
Run Code Online (Sandbox Code Playgroud)
我猜测由于某些原因,MVC正在寻找,System.Web.ModelBinding.IModelBinder但在WebApi的情况下,我已经System.Web.Http.ModelBinding.IModelBinder实施了insteard.
你有什么想法我能解决这个问题吗?
更新:
我发现如果我在我的控制器上评论这个方法:
public void Post([FromBody]MyModel model)
{
//my code here
}
Run Code Online (Sandbox Code Playgroud)
比我没有得到上面的错误.但仍然无法理解为什么我会遇到这样的问题.
这是我的模型细节
public class MyModel : ModelBase
{
}
[ModelBinder(typeof(ModelBaseBinder))]
public class ModelBase
{
}
Run Code Online (Sandbox Code Playgroud)
Ped*_*anz 10
验证模型上的ModelBinderAttribute是否来自System.Web.Http.ModelBinding或System.Web.Mvc.
两者中都有IModelBinder的实现(System.Web.Http.ModelBinding和System.Web.Mvc),并且您的属性与命名空间的命名空间匹配
| 归档时间: |
|
| 查看次数: |
1245 次 |
| 最近记录: |