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.
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.
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.
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.
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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With