create a http server with a delete route in csharp

Here is an example of how to create a HTTP server with a delete route using C# and ASP.NET Web API:

main.cs
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace DeleteExample
{
    public class DeleteController : ApiController
    {
        public IHttpActionResult Delete(string id)
        {
            // Perform delete action based on id parameter
            return Ok();
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Routes.MapHttpRoute(
                name: "DeleteApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { controller = "delete", id = RouteParameter.Optional }, 
                constraints: new { httpMethod = new HttpMethodConstraint("DELETE") }
            );

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Server started");
                Console.ReadLine();
            }
        }
    }
}
1021 chars
37 lines

In the above code, we define a DeleteController class that inherits from ApiController and has a single action method called Delete. This method takes an id parameter and returns an HTTP status code of 200 if the delete action was successful.

We also define a Program class with a Main method that creates a new instance of HttpSelfHostConfiguration with a base URL of http://localhost:8080. We then map a new HTTP route using the RouteCollectionExtensions.MapHttpRoute method where we specify that the route is for the DeleteController and that it should match any URL that is a combination of the base URL, the controller name and an optional id parameter. We also specify that this route should only handle HTTP DELETE requests using the constraints parameter.

Finally, we create a new instance of HttpSelfHostServer and pass in the configuration object. We then open the server and wait for user input to exit the program.

gistlibby LogSnag