更新时间:2023-02-24 09:34:15
好,我已经按照我想要的方式工作了.我不得不修改我为mvc网络api找到的一些类似代码,但使其变得更加简单.如下创建您的自定义模型联编程序并将其添加到globalconfiguration.希望这对其他人有帮助.
Ok, I got this working the way I want. I had to adapt some similar code I found for an mvc web api, but made it a lot simpler. Create your custom model binder as below and add it to the globalconfiguration. Hope this helps someone else.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
GlobalConfiguration.Configuration.BindParameter(typeof(string), new EmptyStringModelBinder());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}"
);
}
}
public class EmptyStringModelBinder : System.Web.Http.ModelBinding.IModelBinder
{
public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
{
string val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
bindingContext.Model = val;
return true;
}
}