在WebAPI中自动创建Controller
在MIS系统中,大部分的操作都是基本的CRUD,并且这样的Controller非常多。
为了复用代码,我们常常写一个泛型的基类。
public class EntityController<T> : ApiController
{
public
IQueryable<T> GetAll()
{
...
}
public
T Get(int id)
{
...
}
public
T Put(int id, Ink ink)
{
...
}
public
T Post(Ink ink)
{
...
}
public
void Delete(int id)
{
...
}
}
当增加一种类型的时候,我们需要手动增加一个子类:
public
class
InkController : EntityController<Ink>
{
}
public
class
PenController : EntityController<Pen>
{
}
当实体模型比较多的时候仍然就存在繁琐和难以维护的问题。因此我们也需要一种自动创建的机制,
要实现自动创建Controller,首先得把现在这种静态创建Controller的方式改成动态创建的方式。在WebAPI中,我们可以通过替换IHttpControllerSelector来实现动态创建Controller。
首先我们实现自己的IHttpControllerSelector。
public
class
MyControllerSelector : DefaultHttpControllerSelector
{
private
readonly
HttpConfiguration _configuration;
public MyControllerSelector(HttpConfiguration configuration)
: base(configuration)
{
_configuration = configuration;
}
public
override
HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
var controllerName = base.GetControllerName(request);
return
new
HttpControllerDescriptor(_configuration, controllerName, typeof(Controllers.EntityController<Ink>));
}
}
然后在初始化函数中注册我们的ControllerSelector
public
static
class
WebApiConfig
{
public
static
void Register(HttpConfiguration config)
{
// Web API configuration and services
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new
MyControllerSelector(GlobalConfiguration.Configuration));
// Web API routes
config.MapHttpAttributeRoutes();
……
}
}
这样一来,即使没有子类InkController,我们同样可以特化泛型控制器EntityController<Ink>实现同样的效果。
到这一步后,还存在一个问题:ControllerSelector只能根据HttpRequest获取ControllerName,并不知道其对应的Model,不知道该如何特化EntityController。解决这个问题的常见的方式就是维护一张Controller名称和实体类型的映射表:
public
class
MyControllerSelector : DefaultHttpControllerSelector
{
static
Dictionary<string, Type> _entityMap;
static MyControllerSelector()
{
_entityMap = new
Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
_entityMap["Ink"] = typeof(Ink);
_entityMap["Pen"] = typeof(Pen);
}
private
readonly
HttpConfiguration _configuration;
public MyControllerSelector(HttpConfiguration configuration)
: base(configuration)
{
_configuration = configuration;
}
public
override
HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
var controllerName = base.GetControllerName(request);
Type entityType = null;
if (!_entityMap.TryGetValue(controllerName.ToLower(), out entityType))
{
return
base.SelectController(request);
}
return
new
HttpControllerDescriptor(_configuration, controllerName, typeof(Controllers.EntityController<>).MakeGenericType(entityType));
}
}
虽然这样做本身没有什么问题。这种手动维护Controller列表的方式仍然无法达到自动创建Controller的要求,因此我们还需要一种自动生成这种映射表的机制。这里我仍然是采用同前文一样的Attribute+反射的方式。
首先写一个ControllerAttribute,
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public
class
ControllerAttribute : Attribute
{
public
string Name { get; private
set; }
public ControllerAttribute(string name)
{
this.Name = name;
}
}
然后,在数据模型中标记该Attribute
[Controller("Pen")]
public
class
Pen
[Controller("Ink")]
public
class
Ink
最后,根据反射建立Controller名称和类型的关联关系
static
Dictionary<string, Type> _entityMap;
static MyControllerSelector()
{
var assembly = typeof(MyControllerSelector).Assembly;
var entityTypes = from type in assembly.GetTypes()
let controllerAtt = type.GetCustomAttribute<ControllerAttribute>()
where controllerAtt != null
select
new { Type = type, ControllerName = controllerAtt.Name };
_entityMap = entityTypes.ToDictionary(i => i.ControllerName, i => i.Type, StringComparer.OrdinalIgnoreCase);
}
这样基本上就可以用了。最后顺手做一下优化,减少的HttpControllerDescriptor创建操作,最终版本的ControllerSelector如下。
public
class
MyControllerSelector : DefaultHttpControllerSelector
{
private
Dictionary<string, HttpControllerDescriptor> _controllerMap;
public MyControllerSelector(HttpConfiguration configuration)
: base(configuration)
{
var entityTypes = from type in
typeof(MyControllerSelector).Assembly.GetTypes()
let controllerAtt = type.GetCustomAttribute<ControllerAttribute>()
where controllerAtt != null
select
new { Type = type, ControllerName = controllerAtt.Name };
_controllerMap = entityTypes.ToDictionary(
i => i.ControllerName,
i => new
HttpControllerDescriptor(configuration, i.ControllerName,
typeof(Controllers.EntityController<>).MakeGenericType(i.Type)),
StringComparer.OrdinalIgnoreCase);
}
public
override
HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
HttpControllerDescriptor controllerDescriptor = null;
if (!_controllerMap.TryGetValue(base.GetControllerName(request), out controllerDescriptor))
{
return
base.SelectController(request);
}
else
{
return controllerDescriptor;
}
}
}
在WebAPI中自动创建Controller的更多相关文章
- 在Code First中自动创建Entity模型
之前我在博客文章中介绍过如何使用Code First来创建数据库,通过CodeFirst的方式,可以大幅的减少开发人员的工作量,比传统的先创建库再ORM的方式简单了不少.但是,很多时候,特别是一些MI ...
- ExtJS6的中sencha cmd中自动创建案例项目代码分析
在之前的博文中,我们按照sencha cmd的指点,在自己win7虚拟机上创建了一个案例项目,相当于创建了一个固定格式的文档目录结构,然后里面自动创建了一系列js代码.这是使用sencha cmd自动 ...
- Xcode6中如何修改文件中自动创建的Created by和Copyright
转自: http://blog.csdn.net/bjourney/article/details/46832159 在Xcode6创建问的时候,会自动生成注释 // Created byxxx o ...
- 在 Xcode中 修改文件中自动创建的Created by和Copyright
在Xcode里创建的时候,会自动生成注释 // Created byxxx on 15/7/10. // Copyright (c) 2015年 xxxx. All rights reserved ...
- 浅谈ETL架构中ODS的作用以及如何在HaoheDI中自动创建ODS表
什么是ODS表? 在ETL架构中,源数据很少会直接抽取加载到数据仓库EDW,二者之间往往会设置一个源数据的临时存储区域,存储数据在清洗转换前的原始形态,通常被大家称做操作型数据存储,简称ODS,在Ki ...
- 013_使用 user.txt 文件中的人员名单,在计算机中自动创建对应的账户并配置初始密码
for i in `cat user.txt`do useradd $i echo "123456" | passwd --stdin $idone
- 转载:性能优化——统计信息——SQLServer自动更新和自动创建统计信息选项
这段时间AX查询变得非常慢,每天都有很多锁. 最后发现是数据库统计信息需要更新. ----------------------------------------------------------- ...
- 性能优化——统计信息——SQLServer自动更新和自动创建统计信息选项
原文:性能优化--统计信息--SQLServer自动更新和自动创建统计信息选项 原文译自:http://www.mssqltips.com/sqlservertip/2766/sql-server-a ...
- [.NET] WebApi 生成帮助文档及顺便自动创建简单的测试工具
==========最终的效果图========== ==========下面开始干活:生成帮助文档========== 一.创建 WebApi 项目 二.找到 HelpPageConfig.cs 并 ...
随机推荐
- Unity3D之实现背景的无限重复生成
在制作flappyBird这个小游戏中(摄像机为Orthographic),为了无限重复生成背景,可以先做好三个背景(我做的有点小),在Gamecontroller上挂一个脚本,如下: pu ...
- ZeroMQ - 三种模型的python实现
ZeroMQ是一个消息队列网络库,实现网络常用技术封装.在C/S中实现了三种模式,这段时间用python简单实现了一下,感觉python虽然灵活.但是数据处理不如C++自由灵活. 1.Request- ...
- asp.net将页面内容按需导入Excel,并设置excel样式,下载文件(解决打开格式与扩展名指定的格式不统一的问题)
//请求一个excel类 Microsoft.Office.Interop.Excel.ApplicationClass excel = null; //创建 Workbook对象 Microsoft ...
- 第二个Sprint冲刺事后诸葛亮报告
用户反馈:计时的填空题难度过大,计时选择题的画面太亮. 用户数量:4 团队改进建议:bug有点多 工作: 主界面 试卷题,是整合以前的内容的 选择题:也是整合以前功能的 初级的 计时题 1.每个成员第 ...
- sscanf,sscanf_s及其相关用法
#include<stdio.h> 定义函数 int sscanf (const char *str,const char * format,........); 函数说明 sscanf ...
- 一个基于ANTLR 4的布尔表达式语句解释器的实现
Reference The Definitive ANTLR 4 Reference, 2nd Edition. 0 Features labeled grammar definition, i.e. ...
- 腾讯优测-优社区干货精选 | 那些年,我们在Android机型适配上遇到的坑之Camera拍照时快门咔嚓声
文/腾讯优测研发工程师 吴宇焕 优测小优有话说: android机型适配的坑自然是不少,不想掉坑快来优测优社区~ 现在Android手机一般都会带有照相功能,有很多朋友就发现手机照相时快门声音很响,想 ...
- 判断JS是否加载完成
在正常的加载过程中,js的加载都是同步的,也就是在加载过程中,浏览器会阻塞接下来的内容的加载.这时候我们就要用到动态加载,动态加载是异步的,如果我们在后边要用到这个动态加载的js文件里的东西,就要保证 ...
- 导航position:absolute
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="C ...
- odoo.cli.main()指的是哪里?OpenERP的第二根线头儿
接上回,odoo-bin中调用了odoo.cli.main(),去哪儿找? cli目录容易找 跟随__init__.py的脚步 import logging import sys import os ...