In our previous edition, I’ve done a small app with OWIN. Although OWIN’s been around for quite a while (and probably due to be replaced by .net core?) there wasn’t a lot of incentive for developers to use it. Maybe, there are but given that most developers that work on C# will host it on IIS, it made a lot of sense to use the standard approach.
So today, I’m going to expand on what we covered with “how do we tie in Web API with OWIN?”
Handily, there’s an app middle-ware for that!
So let’s expand on our previous working example of OWIN and create an api controller.
public class HelloController : ApiController { public object Get(string id) { return new {ID = string.Format("Hello {0}!", id)}; } }
Next, let’s define a HttpConfiguration to deal with the routing things.
public class WebApiConfig : HttpConfiguration { public WebApiConfig() { ConfigureRoutes(); ConfigureSerializer(); } private void ConfigureRoutes() { Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter.Optional} ); } private void ConfigureSerializer() { var jsonSettings = Formatters.JsonFormatter.SerializerSettings; jsonSettings.Formatting = Formatting.Indented; jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } }
So here all pretty normal, but do we tie them all up? We add this code to the ‘Startup.cs’ file.
app.UseWebApi(new WebApiConfig()); //added support for webapi
and it’s all done! Simples! source code here.