C# http监听之Nancy.net

通过winform或者是控制台应用程序监听http请求,之前使用的是微软的HttpListener,参考https://www.cnblogs.com/duanjt/p/5566336.html

然后这篇文章是介绍Nancy.net的使用方式。具体如下:

首先nuget引用:

Install-Package Nancy
Install-Package Nancy.Hosting.Self

然后就是创建一个类继承于Nancy.NancyModule:

public class SampleModule : Nancy.NancyModule
{
    public SampleModule()
    {
        Get["/"] = r =>
        {
            String name = Request.Query.name;//获取get方式提交的参数值
            //Request.Form 用于获取request的请求
            //Request.Body 二进制的请求可以这么获取
            return "hello world," + name;
        };
    }
}

最后就是在主方法里面绑定端口:

class Program
{
    public static void Main(string[] args)
    {
        NancyHost nancySelfHost = new NancyHost(new Uri("http://localhost:8005/"));
        nancySelfHost.Start();
        Console.ReadKey();
    }
}

ok,至此运行控制台应用程序后,就可以通过输入http://localhost:8005进行访问了,将返回hello world

注意:

1.nuget的应用中Nancy.Hosting.Self表示宿主,不要重复引用其它宿主,否则可能造成冲突。这个宿主代表winform或控制台这种

2.类SampleModule 一定要是public的修饰符,否则可能无法加载而出现404

原文地址:https://www.cnblogs.com/duanjt/p/9324326.html