user1073472
user1073472

Reputation: 139

c# Adding web functionality to a windows forms project

I am running a windows forms application on a server which do many things. My intention is to get some web functionality to the application, for example view the logfile in a browser or manipulate the Settings.Defaults via browser.

Is it possible to add the web functionality to a winforms application ?

Upvotes: 1

Views: 804

Answers (1)

Muhammad Nagy
Muhammad Nagy

Reputation: 226

Yes, you can by self hosting web API into your windows form application like demonstrated here

The second option is to use ASP.NET 5 self-hosting but it is still in beta and has no good documentation yet.

Edit 1: To support viewing pages using Web API 2 you need to follow the following steps: First, let JSON formatter handle HTML requests like the following

config.Routes.MapHttpRoute(
  "API Default", "api/{controller}/{id}",
  new { id = RouteParameter.Optional });

// Add the supported media type.            
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Second, Save the desired html template files on disk with placeholders that will be replaced with your actual data at runtime and change the controller like below

    public String GetAllProducts()
    {
        //Should be loaded from HTML template file ex. Products.html
        string html = "<html><body><table border=\"2\"><tr><th>ID</th><th>Name</th><th>Category</th><th>Price</th><tr>{{placeholder}}</table></body></html>";
        StringBuilder sb = new StringBuilder();
        foreach (var item in products)
        {
            sb.AppendLine("<tr><td>" + item.Id + "</td><td>" + item.Name + "</td><td>" + item.Category + "</td><td>" + item.Price + "</td></tr>");
        }
        return html.Replace("{{placeholder}}", sb.ToString());
    }

Note: If you don't like the default JSON formatter you can write your own like there did tn this project

Upvotes: 2

Related Questions