ASP.NET Core MVC Tutorial 2 — Attribute Routes/ActionResults

In this tutorial I will talk about what attribute routes are as well as their uses I will also briefly go through Action Results and give examples of this.

Attribute routes

Firstly, routing is the process of determining a url that maps a browser request to a specific MVC controller action. MVC 5 has support for another type of routing named “Attribute Routing”, a reason as to why this is useful is that it enables the functionality of defining routes above a controllers action method using something called “attributes”. Another purpose for this may be that you want a descriptive action method name so the developer knows what the method does, however, you also want an easy to remember url route for the user to remember. In addition, with attribute routing it is easier to define routes which have a hierarchy of resources such as /product/item/id


public class HelloWorldController:Controller
{
public string Index()
{
return "Index...";
}


}
[Route("HelloWorld")]
public class HelloWorldController:Controller
[Route("")]
public string Index()
{
return "Index...";
}
[Route("favourite")]
public string GetFavouriteDessert()
{
return "My favourite dessert is sticky toffee pudding!";
}
[Route("worst/dessert/{id:int}")]
public string GetWorstDessert(int id)
{
return $"My worst dessert is fruit salad and it has an id of: {id}";
}

ActionResults

I believe I may have touched upon this in the previous article, however, I wanted to give more examples of its usage.

[Route("dinner")]

public ContentResult Dinner()
{
return Content("Hello world this is the dinner route!");
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public ObjectResult Student()
{
var student = new Student {ID = 1, Age = 321, Name = "Santa Claus"};
}
[Route("student")]

public ObjectResult Student()
{
var student = new Student {ID = 1, Age = 321, Name = "Santa Claus"};
return new ObjectResult(student);
}

Software Developer in the UK. With a keen passion for React Native & C#. Blog — https://cowboycode.co.uk/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store