Nancy 寄宿IIS

原文: Nancy 寄宿IIS

一:简介

  • Nancy是一个轻量级的独立的框架,下面是官网的一些介绍:
  • Nancy 是一个轻量级用于构建基于 HTTP 的 Web 服务,基于 .NET 和 Mono 平台,框架的目标是保持尽可能多的方式,并提供一个super-duper-happy-path所有交互。
  • Nancy 设计用于处理 DELETEGETHEADOPTIONSPOSTPUT 和 PATCH 等请求方法,并提供简单优雅的 DSL 以返回响应。
  • Nancy和Asp.net MVC原理相似,但有自己的一套路由机制,在使用上更加易用,可以用Nancy快速开发一些网站。
  • Nancy并不依赖任何现有的框架,所以他可以运行在任何平台上面。

二:创建空白的项目

三:引用nancy类库文件 Nancy.dll  和 Nancy.Hosting.AspNet.dall文件

    public class HomeModule : NancyModule
    {
        public HomeModule()
        {
            Get["/home/get"] = parameters => "Hello World";
        }
    }

    public class HomeModule : NancyModule
    {
        public HomeModule():base("/home")
        {
            Get["/home/get"] = parameters => "Hello World";
        }
    }

四、将Nancy项目发布到IIS中

    public class HomeModule : NancyModule
    {
        public HomeModule() : base("/home")
        {
            //同步
            Get["/get/{name}"] = parameters =>
            {
                return parameters.Name;
            };

            Post["/GetMore"] = p =>
            {
                var name = Request.Form["name"];
                var age = Request.Form["age"];
                var address = Request.Form["address"];
                return $"姓名{name},年龄{age},地址{address}";
            };

            //异步
            Get["/GetOne", true] = async (p, k) =>
            {
                return "这是一个异步的get请求";
            };

            Post["/Add", true] = async (p, k) =>
            {
                var name = Request.Form["name"];
                var age = Request.Form["age"];
                var address = Request.Form["address"];
                var phone = Request.Form["phone"];
                return $"姓名{name},年龄{age},地址{address},手机{phone}";
            };
        }
    }

五、新建项目请求

Get请求
      HttpClient client = new HttpClient();
      var result = await client.GetAsync("http://localhost:166/home/Getone");
      var p = result.Content.ReadAsStringAsync().Result;
Post请求

             HttpContent content = new StringContent("name=xiaoming&age=20&address=beijingchaoyang&phone=15212341234");
            //如果不正确会导致Request.From 获取不到数据
            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            HttpClient client = new HttpClient();
            var result = await client.PostAsync("http://localhost:166/home/Add", content);
            var p = result.Content.ReadAsStringAsync().Result;

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9067965.html