2015-10-20 59 views
4

我有以下型号查询字符串模型绑定ASP.NET的WebAPI

public class Dog 
{ 
    public string NickName { get; set; } 
    public int Color { get; set; } 
} 

,我已经代表通过API暴露现在

public class DogController : ApiController 
{ 
    // GET /v1/dogs 
    public IEnumerable<string> Get([FromUri] Dog dog) 
    { ...} 

以下API控制器的方法,我想发出GET请求如下:

GET http://localhost:90000/v1/dogs?nick_name=Fido&color=1 

问题:如何将查询字符串参数nick_name绑定到属性Ni ckName在狗课上?我知道我可以不用下划线(即昵称)来调用API,也不需要将NickName更改为Nick_Name并获取值,但我需要名称保持与常规一样。

编辑 这个问题是不是重复,因为它是关于ASP.NET的WebAPI不是ASP.NET MVC 2

+0

您的问题是关于将模型属性绑定到别名,是否正确? [这个答案](http://stackoverflow.com/a/4316327/1454538)在那个职位上就是这样。 – mezmi

+1

实现System.Web.Mvc.IModelBinder和System.Web.Http.ModelBinding.IModelBinder是有区别的。对于MVC的BindModel是[对象BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)],对于WebApi是[bool BindModel(HttpActionContext actionContext,\t ModelBindingContext bindingContext)]。我在你的例子中看到可能的复制只覆盖MVC而不是WebApi – dimpho

回答

3

实施IModelBinder

public class DogModelBinder : IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelType != typeof(Dog)) 
     { 
      return false; 
     } 

     var model = (Dog)bindingContext.Model ?? new Dog(); 


     var hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName); 

     var searchPrefix = (hasPrefix) ? bindingContext.ModelName + "." : ""; 

     model.NickName = GetValue(bindingContext, searchPrefix, "nick_name"); 

     int colorId = 0; 
     if (int.TryParse(GetValue(bindingContext, searchPrefix, "colour"), out colorId)) 
     { 
      model.Color = colorId; // <1> 
     } 

     bindingContext.Model = model; 

     return true; 
    } 

    private string GetValue(ModelBindingContext context, string prefix, string key) 
    { 
     var result = context.ValueProvider.GetValue(prefix + key); // <4> 
     return result == null ? null : result.AttemptedValue; 
    } 
} 

,创造ModelBinderProvider

public class DogModelBinderProvider : ModelBinderProvider 
{ 
    private CollectionModelBinderProvider originalProvider = null; 

    public DogModelBinderProvider(CollectionModelBinderProvider originalProvider) 
    { 
     this.originalProvider = originalProvider; 
    } 

    public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType) 
    { 
     // get the default implementation of provider for handling collections 
     IModelBinder originalBinder = originalProvider.GetBinder(configuration, modelType); 

     if (originalBinder != null) 
     { 
      return new DogModelBinder(); 
     } 

     return null; 
    } 
} 

和在控制器中使用的东西,如

public IEnumerable<string> Get([ModelBinder(typeof(DogModelBinder))] Dog dog) 
{ 
    //controller logic 
} 
+0

如何使用这种方法进行数组类型属性? –