Search code examples
c#winformsrestgrapevine

WinForms REST API Server With Grapevine


I would like to add a REST API server to my WinForms application. I have chosen to use Grapveine for that purpose.

Here's my code:

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;
    }
  }
}

Currently I have no idea how to actually access my Form object from the REST route (without using an ugly global/static variable).

How would one do that elegantly?


Solution

  • If you want the current form (or any other object/variable in your project) to be accessible to your routes, you can take advantage of Dynamic Properties. Both the IRestServer and IHttpContext implement IDynamicProperties, which gives you two ways to accomplish your goal.

    Add either of these to your Form1_Load() method.

    Add a Reference On The Server

    server.Properties.Add("CurrentForm", this);
    

    Add a BeforeRouting Event Handler

    server.Router.BeforeRouting += cxt =>
    {
        cxt.Properties.Add("CurrentForm", this);
    };
    

    Access a Property In a Route

    In either case, you can access the property using the built in extensions methods:

    // On the server
    var form = context.Server.GetPropertyValueAs<Form1>("CurrentForm");
    
    // On the context
    var form = context.GetPropertyValueAs<Form1>("CurrentForm");