Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Routing with ASP.NET Web API

Suppose that I have a nested one to many-type hierarchy database as follows:

One Region has many Countries; each Country has many Cities; a City must belong to one and only one country.

Abstracting this information into a RDBMS is a trivial exercise, but (to my mind) the most sensible REST endpoint to return a list of countries for a given region id would be something like the following:

HTTP GET http://localhost/Region/3/Countries

By default, the .NET Web API's routing would be, at best, http://localhost/Countries/Region/3 or http://localhost/Region/Countries/3.

Is there a sensible naming-convention I should follow, or is the routing customisable enough to allow URIs to take any shape I like?

like image 393
Richard A. Avatar asked Jan 15 '13 13:01

Richard A.


People also ask

How do I create a route in Web API?

Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.

What is net core routing in Web API?

Routing in ASP.NET Core Web API application is the process of mapping the incoming HTTP Request (URL) to a particular resource i.e. controller action method. For the Routing Concept in ASP.NET Core Web API, we generally set some URLs for each resource.

What is custom routing in MVC?

In the custom routing mode MVC sites respond to incoming requests using standard ASP.NET routing. Page URLs are determined by the routes that you register into your MVC application's routing table.

How do API routes work?

API routes provide a solution to build your API with Next.js. Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page . They are server-side only bundles and won't increase your client-side bundle size.


1 Answers

The routing should be customizable enough to get the URLs you're looking for. Assuming you want URLs in the form 'http://localhost/Region/3/Countries', you could register this custom route:

config.Routes.MapHttpRoute("MyRoute", "Region/{regionId}/Countries", new { controller = "Region", action = "GetCountries" });

This would dispatch requests to the 'GetCountries' action on the 'RegionController' class. You can have a regionId parameter on the action that gets model bound automatically for you from the URI.

You may want to look online for the attribute routing package for WebAPI since it may be more appropriate in your case.

like image 104
Youssef Moussaoui Avatar answered Oct 02 '22 22:10

Youssef Moussaoui