我有以下型号
public class Dog
{
public string NickName { get; set; }
public int Color { get; set; }
}
我有以下通过API公开的api控制器方法
public class DogController : ApiController
{
// GET /v1/dogs
public IEnumerable<string> Get([FromUri] Dog dog)
{ ...}
现在,我想按如下方式发出GET请求:
GET http://localhost:90000/v1/dogs?nick_name=Fido&color=1
问题:如何将查询字符串参数nick_name绑定到dog类中的属性NickName?我知道我可以在不使用下划线(即昵称)的情况下调用API,或者将NickName更改为Nick_Name并获取值,但我需要保留名称以保持常规。
修改的 这个问题不是重复的,因为它是关于ASP.NET WebApi而不是ASP.NET MVC 2
答案 0 :(得分: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
}