Goodbye Web API: Your Guide to RESTful APIs with ASP.NET Core

By: mwatson
  |  February 28, 2024
Goodbye Web API: Your Guide to RESTful APIs with ASP.NET Core

When ASP.NET Core was released, Microsoft and the .NET community decided to merge the functionality of MVC and Web API. This makes sense since the two have always been very similar. We went through the process of making an ASP.NET Core Web API with various scenarios and came up with these tips for anyone out there wanting to do the same. Are you looking to implement a Web API with ASP.NET Core? Here’s how to accomplish exactly that.

In this article, you’ll learn about

  • Web API vs MVC
  • Migrating Web API to MVC 6
  • Using ASP.NET Core MVC 6 as a RESTful API
  • MVC 6 alternatives for RESTful APIs

ASP.NET Web API vs MVC: What is the Difference?

Before ASP.NET Core, they were very similar. Both followed an MVC type pattern with controllers and actions. Web API lacked a view engine like a Razor and instead was designed to be used for REST APIs. MVC was designed for standard web applications with HTML front ends.

Microsoft touted Web API as a framework for building any type of HTTP service. It was a great alternative to WCF, SOAP, and older ASMX style web services. It was designed from the ground up with JSON and REST in mind. Web API also supported OData, which was a standard way to query data via CRUD operations.

Migrate Existing Web API Controllers by Using a Compatibility Shim

The base class for Web API was ApiController, which no longer exists in ASP.NET Core. You can include the NuGet package for Microsoft.AspNetCore.Mvc.WebApiCompatShim and still use ApiController.

If you are using HttpResponseMessage in your Web API controllers, you will need to make one small code change in your Startup class to call AddWebApiConventions(). This will wire up the HttpResponseMessageOutputFormatter so that it knows how to properly serialize that response.

public void ConfigureServices(IServiceCollection services)
{
	// Add framework services.
	services.AddMvc().AddWebApiConventions(); //Add WebApi
}

Depending on how you want to do routing with Web API, you may also need to register routes for it within your Startup class.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
	app.UseMvc(routes =>
	{
		routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
	});
}

That is all you need to do, and you can migrate your existing Web API code to ASP.NET Core.

Here is a sample controller showing a couple different ways to use your ApiController within ASP.NET Core with the compatibility shim.

[Route("api/[controller]/[action]")]
public class ValuesApiController : ApiController
{
	[HttpGet]
	[ActionName("GetArray")]
	public IEnumerable GetArray()
	{
		//example returns a basic type that is automatically serialized as json - nothing special here
		return new string[] { "value2", "value3" };
	}
	[HttpGet]
	[ActionName("GetSomeJson")]
	public HttpResponseMessage GetSomeJson()
	{
		//example returns a HttpResponseMessage - the shim makes this possible
		var resp = new HttpResponseMessage()
		{
			Content = new StringContent("[{\"Name\":\"ABC\"},[{\"A\":\"1\"},{\"B\":\"2\"},{\"C\":\"3\"}]]")
		};
		resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
		return resp;
	}
}

This article also has a lot of good details about using the compatibility shim: Migrating from ASP.NET Web API to MVC 6 – exploring Web API Compatibility Shim.

Using the New ASP.NET MVC 6 Controllers to Act as a RESTful Web API

The new MVC 6 that ships with ASP.NET Core merges the best of both MVC and Web API worlds from ASP.NET. From any controller, you can return a View or object and MVC will take care of serializing it for you. Multiple different routing styles enable you to implement basic MVC web applications or more REST-style APIs.

Here is a bunch of random ways MVC can be implemented if you wanted a Frankenstein mix up of actions.

public class HomeController : Controller
{
	public IActionResult Index()
	{
		return View("Index"); //MVC view
	}
	public IEnumerable GetArray()
	{
		//example returns a basic type that is automatically serialized as json
		return new string[] { "value2", "value3" };
	}
	public object GetSomeObject()
	{
		//example returns an object that is automatically serialized as json
		return new {color = "red", today = DateTime.UtcNow};
	}
	public IActionResult CreateSomething()
	{
		return StatusCode(201); //set status code
	}
	public string Greet(string id)
	{
		return $"Hello {id}";
	}
}

If you are serious about making a REST-style API, the default ASP.NET project in Visual Studio will create a sample API designed around GET, POST, PUT, DELETE standard operations for REST API. Microsoft also has a good tutorial on their site.

Nancy is a Good Web API Alternative for ASP.NET Core

Outside of the standard MVC framework that ships with ASP.NET, there are some community alternatives. One of the most popular is called Nancy. It has been around for quite a long time and was a popular option for web apps built with Mono to run on Linux since it allowed ASP.NET to work without IIS or the standard System.Web pipeline.

Nancy has a few principles that make it an interesting:

  • Super lightweight
  • Request path matching (routing) and parameter handling
  • Can run on any host including IIS, Kestrel, Owin, self-hosted, etc.
  • View engine integration (Razor and others)

My favorite feature of Nancy is how it works with incoming parameters. This simple example will give you an idea of how it works. Be sure to check out their GitHub page for more details and lots of samples.

public class Module : NancyModule
{
    public Module()
    {
        Get("/greet/{name}", x => {
            return string.Concat("Hello ", x.name);
        });
    }
}

Summary on Web API for ASP.NET Core

Web API may not be available for ASP.NET Core, but you can use your old code with the compatibility shim. We also covered how to just use MVC 6. There are some other 3rd party RESTful API solutions like Nancy that you could also consider. Also check out our post about the top ASP.NET Core features.

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]