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

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

When ASP.NET Core used to be released, Microsoft and the .NET neighborhood determined to merge the performance of MVC and Web API. This makes feel considering that the two have constantly been very similar. We went thru the system of making an ASP.NET Core Web API with a number situations and got here up with these guidelines for all of us out there trying to do the same. Are you searching to put in force a Web API with ASP.NET Core? Here’s how to accomplish precisely that.

In this article, you’ll study about

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

Before ASP.NET Core, they have been very similar. Both accompanied an MVC kind sample with controllers and actions. Web API lacked a view engine like a Razor and rather used to be designed to be used for REST APIs. MVC used to be designed for wellknown net functions with HTML the front ends.

Microsoft touted Web API as a framework for constructing any kind of HTTP service. It was once a magnificent choice to WCF, SOAP, and older ASMX style internet services. It was once designed from the floor up with JSON and REST in mind. Web API additionally supported OData, which was once a trendy way to question facts by using CRUD operations.

Migrate Existing Web API Controllers via Using a Compatibility Shim

The base classification for Web API was once ApiController, which no longer exists in ASP.NET Core. You can encompass the NuGet bundle for Microsoft.AspNetCore.Mvc.WebApiCompatShim and nevertheless use ApiController. The code is on GitHub if you are curious as to what it does.

If you are the use of HttpResponseMessage in your Web API controllers, you will want to make one small code exchange in your Startup category to name AddWebApiConventions(). This will wire up the HttpResponseMessageOutputFormatter so that it is aware of how to proper serialize that response.

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

Depending on how you choose to do routing with Web API, you might also also want to register routes for it inside 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 current Web API code to ASP.NET Core.

Here is a pattern controller displaying a couple exceptional approaches to use your ApiController inside 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 additionally has a lot of appropriate small print about the use of 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 exceptional of each 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 patterns allow you to enforce primary MVC net functions or greater REST-style APIs.

Here is a bunch of random approaches MVC can be applied if you desired a Frankenstein combine 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 mission in Visual Studio will create a pattern API designed round GET, POST, PUT, DELETE widespread operations for REST API. Microsoft additionally has a suitable tutorial on their site.

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

Outside of the trendy MVC framework that ships with ASP.NET, there are some neighborhood alternatives. One of the most famous is referred to as Nancy. It has been round for pretty a lengthy time and was once a famous alternative for net apps constructed with Mono to run on Linux because it allowed ASP.NET to work besides IIS or the fashionable System.Web pipeline.

Nancy has a few concepts that make it an interesting:

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

My preferred function of Nancy is how it works with incoming parameters. This easy instance will provide you an thinking of how it works. Be positive to take a look at out their GitHub web page for extra important points and plenty 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 can also now not be on hand for ASP.NET Core, however you can use your historic code with the compatibility shim. We additionally protected how to simply use MVC 6. There are some different third celebration RESTful API options like Nancy that you may want to additionally consider. Also take a look at out our submit about the pinnacle ASP.NET Core features.

135 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

one + 10 =

You May Also Like