不用属性也能得到类似的效果
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://*:8080/");
listener.Start();
while (true)
{
HttpListenerContext ctx = listener.GetContext();
ThreadPool.QueueUserWorkItem((_) =>
{
string methodName = ctx.Request.Url.Segments[1].Replace("/", "");
string[] strParams = ctx.Request.Url
.Segments
.Skip(2)
.Select(s=>s.Replace("/",""))
.ToArray();
var method = this.GetType().GetMethod(methodName);
object[] @params = method.GetParameters()
.Select((p, i) => Convert.ChangeType(strParams[i], p.ParameterType))
.ToArray();
object ret = method.Invoke(this, @params);
string retstr = JsonConvert.SerializeObject(ret);
});
用法是:
http://localhost:8080/getPersonHandler/333
如果你真的想使用 Attributes 那么
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://*:8080/");
listener.Start();
while (true)
{
HttpListenerContext ctx = listener.GetContext();
ThreadPool.QueueUserWorkItem((_) =>
{
string methodName = ctx.Request.Url.Segments[1].Replace("/", "");
string[] strParams = ctx.Request.Url
.Segments
.Skip(2)
.Select(s=>s.Replace("/",""))
.ToArray();
var method = this.GetType()
.GetMethods()
.Where(mi => mi.GetCustomAttributes(true).Any(attr => attr is Mapping && ((Mapping)attr).Map == methodName))
.First();
object[] @params = method.GetParameters()
.Select((p, i) => Convert.ChangeType(strParams[i], p.ParameterType))
.ToArray();
object ret = method.Invoke(this, @params);
string retstr = JsonConvert.SerializeObject(ret);
});
}
然后你可以使用 ashttp://localhost:8080/Person/333
并且你的定义是
class Mapping : Attribute
{
public string Map;
public Mapping(string s)
{
Map = s;
}
}
[Mapping("Person")]
public void getPersonHandler(int id)
{
Console.WriteLine("<<<<" + id);
}