Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Status Description on HttpUnauthorizedResult

Tags:

asp.net-mvc

In my MVC Application I call the HttpUnauthorizedResult class and specify the statusDescription parameter.

if (!canAdd) {
    return new HttpUnauthorizedResult("You do not have access to add");
}

This redirects me too the Login method on the AccountController and I then redirect them to the appropriate screen.

public ActionResult Login(string returnUrl)
{
if (WebSecurity.IsAuthenticated)
{
    return RedirectToAction("AccessDenied");
}
    ViewBag.ReturnUrl = returnUrl;
    return View();
}

My question is how do I take advantage of the Status Descripton parameter, it would be nice to display these details in the AccessDenied view.

like image 282
Trent Stewart Avatar asked Sep 04 '13 04:09

Trent Stewart


People also ask

What is HttpStatusCodeResult?

HttpStatusCodeResult(HttpStatusCode, String) Initializes a new instance of the HttpStatusCodeResult class using a status code and status description. HttpStatusCodeResult(Int32) Initializes a new instance of the HttpStatusCodeResult class using a status code.

How do I return an error in Actionresult?

You should be logging the relevant information to your error log so that you can go through it and fix the issue. If you want to show the error in the form user submitted, You may use ModelState. AddModelError method along with the Html helper methods like Html.

How can we pass the data from controller to view in MVC?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

What are action results in MVC?

An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result. RedirectResult - Represents a redirection to a new URL.


1 Answers

Got the same issue. I used the TempData to set a message, because it is not possible to set a Viewbag.

filterContext.Controller.TempData["message"] = "Access Denied";
filterContext.Result = new HttpUnauthorizedResult();

The HttpUnauthorizedResult redirects me to the login action of my account Controller where i check for (error)messages:

if (TempData.Count > 0)
{
    var message = TempData["message"];
    ModelState.AddModelError("", message.ToString());
}
like image 193
Gerben Avatar answered Nov 15 '22 12:11

Gerben