2018年9月27日 星期四

C# Nancy Simple Web Application


https://dotblogs.com.tw/ricochen/2016/12/22/220117


Visual Studio 2017 > New Project > Windows Desktop > .NET Framework Console Application

Install-Package Nancy.Hosting.Self


Program.cs

using Nancy;
using Nancy.Hosting.Self;
using Nancy.ModelBinding;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

namespace ConsoleApp1
{
    public class User
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public bool IsAdmin { get; set; }
    }

    public class TestModule : NancyModule
    {
        public TestModule()
        {
            Get["/"] = _ => "Hello Nancy from Get request";

            Post["/"] = _ => "Hello Nancy from Post request";

            Get["/Home"] = Post["/Home"] = parameters =>
            {
                var usersmodel = new List<User>();
                usersmodel.Add(new User { Name = "rico" });
                usersmodel.Add(new User { Name = "sherry" });

                this.ViewBag.data = "From Nancy";

                return View["index.sshtml", usersmodel];
            };

            Get["/User/{Name}"] = p =>
            {
                if (p.Name == "rico")
                    return $"Admini user #{p.Name}!";

                else
                    return $"Normal user #{p.Name}!";
            };

            Post["/RequestBody"] = _ =>
            {
                byte[] data = new byte[this.Request.Body.Length];
                this.Request.Body.Read(data, 0, (int)this.Request.Body.Length);
                string body = System.Text.Encoding.Default.GetString(data);
                User user = JsonConvert.DeserializeObject<User>(body);//Install-Package Nancy.Serialization.JsonNet
                return $"Name:{user.Name} Age:{user.Age} IsAdmin:{user.IsAdmin}";
            };

            Post["/Bind"] = _ =>
            {
                var requestPOCO = this.Bind<User>();
                return $"Name:{requestPOCO.Name}";
            };
        }
    }

    public class ClockModule : NancyModule
    {
        public ClockModule()
        {
            Get["/clock"] = (args) => {
                return new Response
                {
                    ContentType = "text/event-stream",
                    Contents = (Stream stream) =>
                    {
                        var data = Encoding.UTF8.GetBytes("retry: 1000\ndata: " + DateTime.Now.ToString() + "\n\n");
                        stream.Write(data, 0, data.Length);
                        stream.Flush();
                    }
                };
            };
        }
    }

    class Program
    {
        public Program()
        {
            Uri uri = new Uri("http://localhost:9487/");
            HostConfiguration hostConfigs = new HostConfiguration
            {
                UrlReservations = new UrlReservations() { CreateAutomatically = true }
            };
            NancyHost host = new NancyHost(hostConfigs, uri);
            host.Start();
            System.Diagnostics.Process.Start(uri.ToString()+"sse.html");
            Console.WriteLine(uri);
        }

        static void Main(string[] args)
        {
            try
            {
                new Program();
                Console.ReadKey();
            } catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}


views/index.html

<html>
<body>
<h4>@ViewBag.data</h4>
@Each
<p>Name:@Current.Name</p>
@EndEach

<div id="clock">1970-01-01</div>
<script>
new EventSource("/clock").onmessage = function(event) {
    document.getElementById("clock").innerHTML = event.data;
};
</script>

</body>
</html>


Test URL

http://127.0.0.1:9487/
http://127.0.0.1:9487/Home
http://127.0.0.1:9487/User/rico
http://127.0.0.1:9487/User/apple

Postman.exe x64

POST http://127.0.0.1:9487/RequestBody > Body > raw:
{"Name":"Rico","Age":"35","IsAdmin":"true"}

POST http://127.0.0.1:9487/Bind > Body < raw + JSON(application/json)
{"Name":"Rico","Age":"35","IsAdmin":"true"}


Server Sent Event
http://127.0.0.1:9487/clock


End

沒有留言:

張貼留言

2023 Promox on Morefine N6000 16GB 512GB

2023 Promox on Morefine N6000 16GB 512GB Software Etcher 100MB (not but can be rufus-4.3.exe 1.4MB) Proxmox VE 7.4 ISO Installer (1st ISO re...