[英]WinForms REST API Server With Grapevine
我想向我的 WinForms 應用程序添加一個 REST API 服務器。 為此,我選擇使用 Grapveine。
這是我的代碼:
namespace RestServerTest
{
public partial class Form1 : Form
{
private RestServer mServer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
mServer = new RestServer();
mServer.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
mServer.Stop();
mServer.Dispose();
}
}
[RestResource]
class MyRoute
{
[RestRoute]
public IHttpContext HelloWorld(IHttpContext context)
{
// Todo: how access form object from here?
context.Response.SendResponse("Hello, world.");
return context;
}
}
}
目前我不知道如何從 REST 路由實際訪問我的 Form 對象(不使用丑陋的全局/靜態變量)。
如何優雅地做到這一點?
如果您希望路由可以訪問當前表單(或項目中的任何其他對象/變量),您可以利用Dynamic Properties 。 IRestServer
和IHttpContext
實現了IDynamicProperties
,它為您提供了兩種實現目標的方法。
將其中任何一個添加到您的Form1_Load()
方法中。
在服務器上添加引用
server.Properties.Add("CurrentForm", this);
添加BeforeRouting
事件處理程序
server.Router.BeforeRouting += cxt =>
{
cxt.Properties.Add("CurrentForm", this);
};
訪問路徑中的屬性
無論哪種情況,您都可以使用內置擴展方法訪問該屬性:
// On the server
var form = context.Server.GetPropertyValueAs<Form1>("CurrentForm");
// On the context
var form = context.GetPropertyValueAs<Form1>("CurrentForm");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.