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

I am using Rider and will create an ASP.NET Core MVC project, you can use Rider too or maybe Visual Studio/Visual Studio Code.

So after the project has finished generating navigate to the “Controllers” folder and add another “Controller” (class file) and call it “HelloWorldController” and inherit the base class “Controller”. Also add a default action method named “Index” which returns a string.


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


}

Now run the project and navigate to “yourlocalhost/HelloWorld” you will see the “Index…” on the screen.

However, say we want to write descriptive method names for programmers but also clean urls for users, we could use an attribute route to specify what the user has to enter into the url to run the controller action.

We will now specify a route that will need to be entered to access the controller methods in the “HelloWorld” file. We need to specify this above the class.

[Route("HelloWorld")]
public class HelloWorldController:Controller

Above the Index action method enter the below.

[Route("")]
public string Index()
{
return "Index...";
}

Since we have set the Route to an empty string when we enter “/HelloWorld” the index method run.

However, if we want to add a detailed action name for a controller so a programmer can understand its and make a pretty url for the user we can use an attribute for this.

[Route("favourite")]
public string GetFavouriteDessert()
{
return "My favourite dessert is sticky toffee pudding!";
}

Above I have a method called “GetFavouriteDessert”, however, we have set a “Route” of dessert. So when we enter HelloWorld/favourite into the url we get the above string shown on the page.

With attribute routing you can even define more than 1 route for the same action.

Furthermore, attribute routing is a great way of establishing hierarchical resources like the below. So we have a route of “worst/dessert/{id:int}” where the id equates to the id parameter of the “GetWorstDessert” action method so what ever is entered into the “id” of the url will return to the screen in the string statement.

[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

An ActionResult is a return type for a method within a controller that returns different kinds of content. The ActionResult type is the base class for all of the action results, however, the ActionResult type may be seen as generic and might not give programmers much perspective on what the method is suppose to do. So below is the list again of each ActionResult and what they return.

ContentResult returns a string.

JsonResult returns JSON data.

JavaScriptResult returns script.

FileContent, FilePath and FileStream returns file content.

View and PartialView are both returned as a response for the chosen view engine.

RedirectToResult will redirect the user to a specific URL.

HttpUnauthorizedResult will return a 403 (Unauthorized) HTTP Status code to the user.

RedirectToRouteResult will redirect to a different controller action within the project.

ObjectResult returns an object (Can even return content inside of an instantiated class)

A very easy example to show would be ContentResult.

Navigate to the HelloWorld controller and write the below.

[Route("dinner")]

public ContentResult Dinner()
{
return Content("Hello world this is the dinner route!");
}

Here we are using the “ContentResult” type and returning a string within the “Content” object which creates a “ContentResult” object that returns the string specified inside the parameters.

Below is an example of what the HelloWorld/dinner route shows to the user.

I will now show an example of an ObjectResult action. So now inside of your “Models” folder create a new class file named Student and inside of it create 3 properties “ID” (int), “Name” (string), ”Age” (int)

So now your Student.cs file in the Models folder should look like the below.

public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}

Now create a new method in the HelloWorldController named Student and set the return type to ObjectResult. Within this method we can make a reference to the student class and set it to a var type.

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

Here I have set mine to be Santa Claus with an ID and Age value.

What we now want to do is just return this object using the ObjectResult and setting the “student” variable as an argument for ObjectResult like below

[Route("student")]

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

Now run your project and navigate to HelloWorld/student. You will see the content of the object on the page.

I hope this tutorial has helped you learn a bit more about routing and action results within ASP.NET Core MVC, if there is anything else I can do to improve this tutorial such as give more examples then please let me know in the responses.

Thanks again for reading and have a great day!

Blog — https://cowboycode.co.uk/

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