在下面的代码中,我正在等待对8080端口的任何调用。
static void Main() { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://*:8080/"); listener.Start(); while(isRunning) { HttpListenerContext ctx = listener.GetContext(); new Thread(new Worker(ctx).ProcessRequest).Start(); } }
是否可以将特定的URL模式映射到不同的行为?我想实现一个REST风格的服务器,即对 localhost:8080 / person / 1 的调用将启动getPersonHandler(int)
[Mapping("*:8080/person/$id")] public void getPersonHandler(int id){...}
该Mapping语法只是我一厢情愿的比喻JAX-RS库,我知道了。我想在C#中执行相同操作(台式C#,而不是ASP)
Mapping
没有属性,您可以获得类似的效果
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
如果您真的想使用属性,那么
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); }); }
然后,您可以使用as http://localhost:8080/Person/333,您的定义将是
http://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); }