这是我一直在玩的一个想法...使用风险自负,代码在我的“沙盒”文件夹中;)
我想我想摆脱使用反射来确定运行哪个方法,使用 HttpVerb 作为键在字典中注册委托可能会更快。无论如何,此代码是没有保修的,废话,废话,废话......
用于 REST 服务的动词
public enum HttpVerb
{
GET, POST, PUT, DELETE
}
用于标记服务方法的属性
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
public class RestMethodAttribute: Attribute
{
private HttpVerb _verb;
public RestMethodAttribute(HttpVerb verb)
{
_verb = verb;
}
public HttpVerb Verb
{
get { return _verb; }
}
}
Rest Service 的基类
public class RestService: IHttpHandler
{
private readonly bool _isReusable = true;
protected HttpContext _context;
private IDictionary<HttpVerb, MethodInfo> _methods;
public void ProcessRequest(HttpContext context)
{
_context = context;
HttpVerb verb = (HttpVerb)Enum.Parse(typeof (HttpVerb), context.Request.HttpMethod);
MethodInfo method = Methods[verb];
method.Invoke(this, null);
}
private IDictionary<HttpVerb, MethodInfo> Methods
{
get
{
if(_methods == null)
{
_methods = new Dictionary<HttpVerb, MethodInfo>();
BuildMethodsMap();
}
return _methods;
}
}
private void BuildMethodsMap()
{
Type serviceType = this.GetType();
MethodInfo[] methods = serviceType.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (MethodInfo info in methods)
{
RestMethodAttribute[] attribs =
info.GetCustomAttributes(typeof(RestMethodAttribute), false) as RestMethodAttribute[];
if(attribs == null || attribs.Length == 0)
continue;
HttpVerb verb = attribs[0].Verb;
Methods.Add(verb, info);
}
}
public bool IsReusable
{
get { return _isReusable; }
}
}
示例 REST 服务
public class MyRestService: RestService
{
[RestMethod(HttpVerb.GET)]
public void HelloWorld()
{
_context.Current.Response.Write("Hello World");
_context.Current.Response.End();
}
}