2015-10-20 60 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

如何使用這種方法進行數組類型屬性? –