Monday, July 11, 2016

Web API with ASP.NET Core MVC

I was exploring the new ASP.NET Core from Microsoft and being on a Mac, to start things off, I was following this guide, which includes setting up .NET Core and Visual Studio Code with the C# extension + scaffolding a template project using Yeoman. Pretty simple and works out of the box.

Now, to get going with Web API, the next guide would be https://docs.asp.net/en/latest/tutorials/first-web-api.html. However, this is based on Visual Studio 2015, where there are ready-made templates for a Web API project. I continued using the guide with my Yeoman template to see how far it would take me.

Turns out that I got pretty far, by just following the examples. The first thing that hit me was the change in the

ConfigureServices
file, namely the
services.AddMvc();
method. There was no notion of a MVC-framework in the generated Yeoman code, and I had to add
"Microsoft.AspNetCore.Mvc": "1.0.0"
to
project.json
to make it compile. To finally get the application to serve my API instead of the generated "Hello World" page, I changed
app.Run(async (context) =>
  {
    await context.Response.WriteAsync("Hello World!");
  });
to
app.UseMvcWithDefaultRoute();
To wrap things up, I changed the default namespace from
EmptyWeb1
to
TodoApi
to make things consistent.

At the very end of the guide, I also found the link to the source code, which could have saved me from figuring things out for myself.

/Mattias

No comments:

Post a Comment