Nancy fx 如何在 Windows 表格中使用

Nancy fx how to use in Windows Forms

这里我有一个简单的 WinForm 应用程序,它有一个运行良好的 NancyFx 服务:我使用一个实现 IPerson 接口的 Person 对象。 nancyModule 有一个参数为 IPerson 的构造函数,在 nancyModule 的 post 路由中我使用 this.Bind();如果我想在表单上显示人物,我该怎么做?

using System;
using System.Windows.Forms;
using Microsoft.Owin.Hosting;
using Nancy;
using Nancy.ModelBinding;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private IDisposable dispose;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           string uri = "http://localhost:8080/";
           dispose = WebApp.Start<Startup1>(uri);
        }
    }

    public interface IPerson
    {
        String Name { get; set; }
    }
    public class Person : IPerson
    {
        public String Name { get; set; }
    }
    public class nancyModule : NancyModule
    {
        public nancyModule(IPerson person)
        {
            Post["/data"] = _ =>
            {
                person = this.Bind<Person>();
                //HOW DO I DISPLAY THE person  ON THE FORM UI
               return HttpStatusCode.OK;
           };
        }
   }
}

如果您想在表单上显示人员数据,则需要从 Win Forms 应用程序调用 REST API。抓取响应并输出结果。简而言之,这就是实现这一目标的方法。

I haven't used async and await keywords which ideally you would but for brevity I have omitted this.

首先,我从您的模块中删除了 IPerson 的依赖项,因为这不是依赖项本身,而是您的 POST 的输出。稍作调整后,它看起来像这样:

如果您仍然强烈认为 IPerson 是一个依赖项,那么只需保留它,代码仍会按预期工作。

public class PersonModule : NancyModule
{
    public PersonModule()
    {
        this.Post["/data"] = args => this.AddPerson();
    }

    private Negotiator AddPerson()
    {
        var person = this.Bind<Person>();

        return this.Negotiate
            .WithStatusCode(HttpStatusCode.Created)
            .WithContentType("application/json")
            .WithModel(person);
    }
}

现在从您的 Win Forms 应用程序只需通过 HttpClient 调用 API,如下所示:

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var person = new Person { Name = "Foo Bar" };
    var serializer = new JavaScriptSerializer();
    var response = client.PostAsync(
        "http://localhost:8080/data",
        new StringContent(serializer.Serialize(person), Encoding.UTF8, "application/json")).Result;
    var result = new JavaScriptSerializer().Deserialize<Person>(response.Content.ReadAsStringAsync().Result);

    TextBox1.Text = result.Forename;
}

Purest's out there will mention 3rd party libraries such as Json.NET and Service Stack which allows for easier serialization and deserialization but again for simplicity in this example I am using out of the box features.