Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用C#HttpListener的URL映射_C#_Http_Url Mapping - Fatal编程技术网

使用C#HttpListener的URL映射

使用C#HttpListener的URL映射,c#,http,url-mapping,C#,Http,Url Mapping,在下面的代码中,我正在等待对8080端口的任何调用 static void Main() { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://*:8080/"); listener.Start(); while(isRunning) { HttpListenerContext ctx = listener.GetContext(); new Thread(n

在下面的代码中,我正在等待对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)


映射
语法只是我自己对我所知道的JAX-RS库的一厢情愿的类比。我希望在C#(桌面C#,而不是asp)中也能做到这一点。

您可以在没有属性的情况下获得类似的效果

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
您的定义将是

class Mapping : Attribute
{
    public string Map;
    public Mapping(string s)
    {
        Map = s;
    }
}

[Mapping("Person")]
public void getPersonHandler(int id)
{
    Console.WriteLine("<<<<" + id);
}
类映射:属性
{
公共字符串映射;
公共映射(字符串s)
{
Map=s;
}
}
[映射(“人”)]
public void getPersonHandler(int id)
{

如果您在.NET 4.0或更高版本中工作,并且正在寻找一个可以插入的现有REST服务器解决方案(听起来像是这样的),则使用Console.WriteLine(),您可能想签出。您可以使用NuGet获得它,并且有很多示例代码。此外,它是开源的,因此如果您只想了解如何实现它,您可以在那里查看所有的源代码

您可以按路径信息(使用正则表达式)和请求方法(GET、POST等)过滤请求


我是项目作者,我有着与您描述的类似的需求。利用我在这里和其他地方找到的资源,我构建了葡萄藤,这样每当我再次需要它时,我的后口袋里就会有一个解决方案().

你真的需要重新发明轮子吗?ASP.NET MVC 4中的Web API可以做到这一点。我需要一个独立的应用程序。仅供参考,ASP.NET Web API可以自托管(无IIS),如果ASP.NET Web API可以在可执行文件中自托管,我希望看到!(不是说它不能,只是我不知道它可以).Use OWIN to self host:@param是什么类型的变量名?因为
params
在c#中是保留字,所以我用
@params
我不知道你可以在变量名中使用
@
,谢谢。我喜欢这个答案。非常感谢。最后一件事:你也可以按请求类型过滤(GET,PUT…)?@elmes
ctx.Request.HttpMethod
Nice项目-我需要在命令行应用程序中加入一个REST API,Grapevine比C#中的stock HttpListener类干净得多。
class Mapping : Attribute
{
    public string Map;
    public Mapping(string s)
    {
        Map = s;
    }
}

[Mapping("Person")]
public void getPersonHandler(int id)
{
    Console.WriteLine("<<<<" + id);
}