Scott Hanselman

Exploring a minimal WebAPI with ASP.NET Core

July 26, '16 Comments [12] Posted in ASP.NET | ASP.NET Web API
Sponsored By

They are still working on the "dotnet new" templates, but you can also get cool templates from "yo aspnet" usingn Yeoman. The generator-aspnet package for Yeoman includes an empty web app, a console app, a few web app flavors, test projects, and a very simple Web API application that returns JSON and generally tries to be RESTful.

yo aspnet

The startup.cs is pretty typical and basic. The Startup constructor sets up the Configuration with an appsettings.json file and add a basic Console logger. Then by calling "UseMvc()" we get to use all ASP.NET Core which includes both centralized routing and attribute routing. ASP.NET Core's controllers are unified now, so there isn't a "Controller" and "ApiController" base class. It's just Controller. Controllers that return JSON or those that return Views with HTML are the same so they get to share routes and lots of functionality.

public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseMvc();
}
}

Then you can make a basic controller and use Attribute Routing to do whatever makes you happy. Just by putting [HttpGet] on a method makes that method the /api/Values default for a simple GET.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace tinywebapi.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}

// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}

// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

If we run this with "dotnet run" and call/curl/whatever to http://localhost:5000/api/Values we'd get a JSON array of two values by default. How would we (gasp!) add XML as a formatting/serialization option that would respond to a request with an Accept: application/xml header set?

I'll add "Microsoft.AspNetCore.Mvc.Formatters.Xml" to project.json and then add one method to ConfigureServices():

services.AddMvc()
        .AddXmlSerializerFormatters();

Now when I go into Postman (or curl, etc) and do a GET with Accept: application/xml as a header, I'll get the same object expressed as XML. If I ask for JSON, I'll get JSON.

 Postman is a great way to explore WebAPIs

If I like, I can create my own custom formatters and return whatever makes me happy. PDFs, vCards, even images.

Next post I'm going to explore the open source NancyFx framework and how to make minimal WebAPI using Nancy under .NET Core.


Sponsor: Thanks to Aspose for sponsoring the feed this week! Aspose makes programming APIs for working with files, like: DOC, XLS, PPT, PDF and countless more.  Developers can use their products to create, convert, modify, or manage files in almost any way. Aspose is a good company and they offer solid products. Check them out, and download a free evaluation!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb
Tuesday, 26 July 2016 09:18:22 UTC
Hey Scott,
nice article. In our company we are also experimenting with .net core and the web api for microservices. So we just found the package "Swashbuckle": "6.0.0-beta901" which helps us documenting our possible microservices in a standard way. Maybe this package could be a nice extension for your article or just a simple follow up article.
More info can be found on the projects homepage : https://github.com/domaindrivendev/Ahoy
Bjego
Tuesday, 26 July 2016 10:06:43 UTC
Hi Scott,

nice article!

What's that Rest-Tool shown in the last screenshot? Looks good!
Frank Wilhelm Aberknall
Tuesday, 26 July 2016 10:16:30 UTC
@Frank - its Postman I have found it really nice to use.
Tuesday, 26 July 2016 11:20:04 UTC
I used NancyFx for a little project about a year ago and it was an actual dream to use. I'd never done any ASP.net or anything webby before, but I was able to pick up NancyFx in a day or two, have it self host a minimal site that handled some file uploads and a basic login system.

It actually gave me a good basis to start with when it came to following asp.net core.
Tuesday, 26 July 2016 14:40:56 UTC
to be really minimal - you probably want to rather use

service.AddMvcCore()

and derive from ControllerBase

Tuesday, 26 July 2016 17:24:19 UTC
Nice post Scott. I have used WebApi in the past and found it to be heavy handed for a rest application, requiring more boilerplate/config than I liked (although its been 3 years!). Lately I have used NancyFx extensively and like Stephen said above it is a dream to use. Your Startup class actually looks very much like a Nancy bootstrapper!
The best parts of Nancy are its simplicity and how easy it is to extend/modify. Do you have any info to share on how easily global behaviors (pipelines in Nancy) can be added/modified? I don't mean this next question to sound confrontational, it is a curious question. Why would I use WebApi when I have such easy Rest libraries like NancyFx and ServiceStack at my disposal?
Shane
Thursday, 28 July 2016 13:04:22 UTC
@Dominic when I was using RC2 and now RTM there is no controller base class. It's all convention based. As long as the class has the controller suffix it will work (at least in my experience of using it thus far). Got examples on git.
Onam
Friday, 29 July 2016 19:09:47 UTC
This is fantastic. It's going to open up a lot of possibilities for new ways of working in the .net community.
Saturday, 30 July 2016 19:06:47 UTC
Thanks for the nudge to grab Postman and try it out. :-) Also thumbs up for the not TL;DR post on exploring web API in ASP.NET Core.
Monday, 01 August 2016 06:50:52 UTC
What kind of scenarios would you use dotnet new if you had Visual Studio 2015?
Peter
Monday, 08 August 2016 13:08:16 UTC
How about example that shows how to add a class library project to ASP .NET Core WEbApi solution?
Leszek
Thursday, 25 August 2016 00:51:54 UTC
+1 for Postman. Amazing tool.
Chris
Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.