HTTP Result in Controller Sample in MVC

HTTP Result in Controller Sample in MVC

Introduction

In this article we will see how to use a HTTP result in a controller in MVC.

Step 1

Create a MVC project from the "Empty" template.

Right-click on "Controllers" and select "Add" >> "Controller...".

image.png

Step 2

Select "MVC 5 Controller - Empty" to add an empty controller.

Click on the "Add" button.

image.png

Step 3

Name the controller as in the following:

image.png

And it will add an action result method to the controller.

image.png

Step 4

Now we need to create a view.

Right-click on "Index" and select "Add View...".

image.png

Step 5

Name the view and select "Empty (without model)" as the template.

Click on the "Add" button.

image.png

Step 6

Add a title to the index page.

image.png

Step 7

Create a httpstatuscoderesult method in the home controller, it returns a HTTP response status code and description. Here we return the "InternalServerError" status code.

image.png

Step 8

Create a link to call the httpStatusCodeResult method.

image.png

Step 9

Run the project, click on "Http Status Code" and you can see the defined message with HTTP response status code 500.0.

image.png

image.png

Step 10

Now let's see an example of HttpUnauthorizedResult.

HttpUnauthorizedResult represents the result of an unauthorized HTTP request.

image.png

Step 11

Create a link to call the httpUnauthorizedResult method.

image.png

Step 12

Run the project, click on "Http Unauthorized" and you can see the defined message with HTTP unauthorized status code.

image.png

image.png

Step 13

So far we have seen HttpStatusCodeResult and HttpUnauthorizedResult, now let's see an example of HttpNotFoundResult.

HttpNotFoundResult defines an object that is used to indicate that the requested result resource was not found.

image.png

Step 14

Create a link to call the httpNotFoundresult method.

image.png

Step 15

Run the project, click on "Http Not Found" and you can see the "File Not Found" message with HTTP response status code.

image.png

image.png

<< Day 13

>> Day 15