Introduction
The Status Action Results will return the status codes to the browser. As part of the Status Result, I will discuss the following three status code.
- HttpStatusCodeResult
- HttpUnauthorizedResult
- HttpNotFoundResult
HttpStatusCodeResult
HttpStatusCodeResult returns an HTTP status code to the browser, along with a custom message to be displayed.
HttpUnauthorizedResult
HttpUnauthorizedResult is the same as HttpStatusCodeResult HttpStatusCode.Unauthorized. It does not allow unauthorized users.
HttpNotFoundResult
This is also an overload of HttpStatusCodeResult, but unlike HttpUnauthorizedResult, it actually does have a helper method
The HttpStatusCode enumeration contains all HTTP status codes (so that you don’t have to remember what 402 or 307 means). These are useful in exception-driven scenarios where you have custom error pages defined. There is no helper method for these ActionResult.
Step 1
Open Visual Studio 2015 or your choice and create a new project.
Step 2
Choose web application project and give an appropriate name for your project.
Step 3
Select an empty template, check the MVC checkbox below, and click OK.
Step 4
Right-click the Controllers folder and add a controller.
A window will appear. Choose MVC5 Controller-Empty and click "Add".
After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.
Here is the complete code for Home Controller
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcStatusResult_Demo.Controllers
- {
- public class HomeController : Controller
- {
-
- public HttpStatusCodeResult BadGateway()
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadGateway,"There is something wrong. please contact admin.");
- }
-
- public HttpStatusCodeResult Unauthorized()
- {
- return new HttpStatusCodeResult(HttpStatusCode.Unauthorized, "You are not authorized to access this controller action.");
- }
-
- public HttpStatusCodeResult NotFound()
- {
- return HttpNotFound("Your request did not find.");
- }
- }
- }
Step 5
Build your project and press ctrl+5 to run the project
http://localhost:61788/home/BadGateway
http://localhost:61788/home/Unauthorized
http://localhost:61788/home/NotFound
Summary
In this article, I tried to explain the Status Result in ASP.NET MVC applications step by step with a simple example. I hope this article will help you.