Category: Rest API

Multiple Ways to Build Routing in ASP.NET Core

url-routing

Routing in Microsoft MVC or WebAPI applications serves as a map to define the routes for all incoming requests. There are three basic components of routing in MVC , WebAPI applications Controller, Action method, and parameters.

Example:

https://www.betechnical.blog/account/login/24

In the provided link account is a controller, login is action method and 24 is parameter or query string.

Let’s review the different ways to build routing in ASP.NET CORE.

Creating Default Routes

By convention in your project’startup class, the default route can be defined.

public class Startup
{
   public void ConfigureServices(IServiceCollection services)
   {
      services.AddMvc();
   }

   public void Configure(IApplicationBuilder app, 
                         IHostingEnvironment env, 
                         ILoggerFactory loggerFactory)
   {

      app.UseMvc(routes =>
      {

         routes.MapRoute(
                         name: "default",
                         template: "
                         {controller=Home}/{action=Index}/{id?}");

       });

    }
}

We need to be sure that essential configuration for MVC pattern of Controller + Action + ID route, exist in our project. Routing pattern can also be declared like: 

routes.MapRoute(
    name: "default_route",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" }
);

Extending Default Routes

On specific needs, Default Route can be extended by adding customized routes. By MapRoute() method, configurations can be added:

app.UseMvc(routes =>
{
    //New Route
    routes.MapRoute(
       name: "about-route",
       template: "about",
       defaults: new { controller = "Home", action = "About" }
    );

    routes.MapRoute(
       name: "default",
       template: "{controller=Home}/{action=Index}/{id?}");
});

On the Home controller, Adding extra route allows access to About action with an/about the route. About page can be still accessed with conventional /home/about the route, as the default pattern route is still present.

Using Attributes

Using attributes in controller and actions, you can also configure routes.

[Route("[controller]")]
public class AnalyticsController: Controller
{

    [Route("Dashboard")]
    public IActionResult Index()
    {
        return View();
    }

    [Route("[action]")]
    public IActionResult Charts()
    {
        return View();
    }
}

Now, controller actions can be accessed through the following routes:

  • /Analytics/Dashboard
  • /Analytics/Charts

Two tokens [controller] and [action] indicate that we have to refer to the controller and action name that has been declared. In this case, “Analytics” is the name of the controller, and “Charts” the name of the action, therefore it the name of the route.

Building RESTful Routes

We need to use the following route configuration, to declare a RESTful controller. 

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable Get()
    {
        return new string[] {"hello", "world!"};
    }

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

    }
}

 

Here, RESTful service is told to accept calls under the /api/values route. Now, we do not use the Route attribute for actions. Instead, we decorate it with HttpGet, HttpPost, HttpPut, HttpDelete attributes

Advertisements

ASP.NET MVC and ASP.NET Web API

confusion-clipart-4c9on8bzi

While developing your web application using MVC, many developers got confused when to use Web API, since MVC framework can also return JSON data by using JsonResult and can also handle simple AJAX requests. In the previous article Web API and WCF the Most poppuler Frameworks of Microsoftt, I have explained the Difference between WCF and Web API and WCF REST and Web Service and when to use Web API over others services. In this article, you will learn when to use Web API with MVC.

Asp.Net Web API VS Asp.Net MVC

  1. Asp.Net MVC is used to create web applications that return both views and data but Asp.Net Web API is used to create full-blown HTTP services with the easy and simple way that returns only data, not view.

  2. Web API helps to build REST-ful services over the .NET Framework and it also supports content-negotiation(it’s about deciding the best response format data that could be acceptable by the client. it could be JSON, XML, ATOM or other formatted data), self-hosting which are not in MVC.

  3. Web API also takes care of returning data in particular format like JSON, XML or any other based upon the Accept header in the request and you don’t worry about that. MVC only return data in JSON format using JsonResult.

  4. In Web API the request is mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.

  5. Asp.Net Web API is a new framework and part of the core ASP.NET framework. The model binding, filters, routing and others MVC features exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these features exist within System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand-alone service layer.

  6. You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML or any others format and be building a full blown HTTP service. Typically, this will be called Web API self-hosting.

  7. When you have mixed MVC and Web API controller and you want to implement the authorization then you have to create two filters one for MVC and another for Web API since both are different.

  8. Moreover, Web API is lightweight architecture and except the web application, it can also be used with smartphone apps.

How to Migrate Existing Web API Controllers by Using a Compatibility Shim

.NET and Microsoft decided to merge the MVC and Web API functionality, after the release of ASP.NET. If you are looking for the implementation of Web API with ASP.NET, Here is the way to accomplish:

Migrating Existing Web API Controllers by Compatibility Shim

You will have to alter one code to call AddWebApiConventions() if you use HttpResponseMessage in Web API controllers. It will help to know the proper serialize that response by wiring up the HttpResponseMessageOutputFormatter.

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

}Depending upon your routing with Web API. You will need to register routes with Startup class.

In this way, you can migrate from your Web API code to ASP.NET Core. 

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

This sample controller helps you to use your ApiController within ASP.NET Core with 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;
	}
}