由于客户端调用Web API传递的数据属性命名一般偏向javascript规范,只是简单的大小写差异没有问题,但始终会有一些特殊情况。比如OAuth的请求:

client_id : "value"
client_secret : "value"

在ASP.NET MVC开发时一般我们会开发一个ModelBinder,如果只是实现别名的绑定,继承DefaultModelBinder即可快速实现。下面的BindAliasModelBinder就是一个简单的实现参考:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class BindAliasAttribute : Attribute
{
public BindAliasAttribute(string name)
{
this.Name = name;
} public string Name { get; set; }
}
public abstract class AttributeModelBinder<TAttribute> : DefaultModelBinder
where TAttribute : Attribute
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor); foreach (var attribute in propertyDescriptor.Attributes)
{
if (attribute is TAttribute)
{
BindPropertyCore(controllerContext, bindingContext, propertyDescriptor, attribute as TAttribute); break;
}
}
} protected abstract void BindPropertyCore(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, TAttribute attribute);
}
public class BindAliasModelBinder : AttributeModelBinder<BindAliasAttribute>
{
protected override void BindPropertyCore(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, BindAliasAttribute attribute)
{
var value = controllerContext.HttpContext.Request.Params[attribute.Name];
propertyDescriptor.SetValue(bindingContext.Model, value);
}
}

然后我们在模型上这么使用它:

[ModelBinder(typeof(BindAliasModelBinder))]
public class OAuthModel
{
[BindAlias("client_id")]
public string ClientId { get; set; } [BindAlias("redirect_uri")]
public string RedirectUri { get; set; }
}

再来看Web API的模型绑定:System.Web.Http.ModelBinding.IModelBinder。只定义了一个方法"BindModel",需要实现和上面BindAliasModelBinder一样的功能有点太复杂了。这里有一个比较偷懒的推荐方式,就是将参数定义为一个JObject对象,调用它提供的ToObject<T>方法转换为实际的模型,这个时候就可以通过JsonPropertyAttribute解决映射的问题。例如:

public AccessTokenResponse AccessToken(JObject content)
{
var request = content.ToObject<AccessTokenRequest>(); }

最新文章

  1. 用CS的思维可以指导BS的项目吗?
  2. insertAfter的兼容性
  3. Delphi经验总结(1)
  4. Codec工具类
  5. rfc的资料
  6. ckplayer网页播放器简易教程
  7. Java调用R——rJava的安装和配置
  8. Vue 普通对象数据更新与 file 对象数据更新
  9. SQL存储过程和函数
  10. RQPro 公募FOF策略实例——晨星基金筛选和风险平价配置
  11. python3基础(一)
  12. Coins、Tokens、山寨币:区别在哪里
  13. Failed building wheel for scandir 解决方案
  14. Mysql 5.7--ubuntu18.04 安装过程及遇到的问题
  15. pyinstaller 打包生成exe之后运行提示‘no module name &#39;xxx&#39;’错误
  16. java中的a++与++a的区别
  17. luanet更名为distri.lua
  18. BeanUtils解决日期问题
  19. for循环练习--杨辉三角
  20. 关于Cocos2d-x中多边形物理刚体的设置

热门文章

  1. mysql用户管理 常用sql语句 mysql数据库备份恢复
  2. mocha框架下,异步测试代码错误造成的问题----用例超时错误
  3. 避免使用jQuery的html方法来替换标签,而是使用replaceWith方法
  4. 查看cp进度,使用watch
  5. swig和angular双花括号的冲突
  6. Maven Missing artifact jar
  7. VC获得本机网络连接状态
  8. redis的有序集合ZSET(stored set)
  9. 动态背景插件Backstretch
  10. python Thread对象的setDaemon(True)的作用。