Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 256531
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T22:01:18+00:00 2026-05-11T22:01:18+00:00

I have a controller in ASP.NET MVC that I’ve restricted to the admin role:

  • 0

I have a controller in ASP.NET MVC that I’ve restricted to the admin role:

[Authorize(Roles = "Admin")]
public class TestController : Controller
{
   ...

If a user who is not in the Admin role navigates to this controller they are greeted with a blank screen.

What I would like to do is redirect them to View that says “you need to be in the Admin role to be able to access this resource.”

One way of doing this that I’ve thought of is to have a check in each action method on IsUserInRole() and if not in role then return this informational view. However, I’d have to put that in each Action which breaks the DRY principal and is obviously cumbersome to maintain.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T22:01:18+00:00Added an answer on May 11, 2026 at 10:01 pm

    Create a custom authorization attribute based on AuthorizeAttribute and override OnAuthorization to perform the check how you want it done. Normally, AuthorizeAttribute will set the filter result to HttpUnauthorizedResult if the authorization check fails. You could have it set it to a ViewResult (of your Error view) instead.

    EDIT: I have a couple of blog posts that go into more detail:

    • http://farm-fresh-code.blogspot.com/2011/03/revisiting-custom-authorization-in.html
    • http://farm-fresh-code.blogspot.com/2009/11/customizing-authorization-in-aspnet-mvc.html

    Example:

        [AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
        public class MasterEventAuthorizationAttribute : AuthorizeAttribute
        {
            /// <summary>
            /// The name of the master page or view to use when rendering the view on authorization failure.  Default
            /// is null, indicating to use the master page of the specified view.
            /// </summary>
            public virtual string MasterName { get; set; }
    
            /// <summary>
            /// The name of the view to render on authorization failure.  Default is "Error".
            /// </summary>
            public virtual string ViewName { get; set; }
    
            public MasterEventAuthorizationAttribute()
                : base()
            {
                this.ViewName = "Error";
            }
    
            protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
            {
                validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
            }
    
            public override void OnAuthorization( AuthorizationContext filterContext )
            {
                if (filterContext == null)
                {
                    throw new ArgumentNullException( "filterContext" );
                }
    
                if (AuthorizeCore( filterContext.HttpContext ))
                {
                    SetCachePolicy( filterContext );
                }
                else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    // auth failed, redirect to login page
                    filterContext.Result = new HttpUnauthorizedResult();
                }
                else if (filterContext.HttpContext.User.IsInRole( "SuperUser" ))
                {
                    // is authenticated and is in the SuperUser role
                    SetCachePolicy( filterContext );
                }
                else
                {
                    ViewDataDictionary viewData = new ViewDataDictionary();
                    viewData.Add( "Message", "You do not have sufficient privileges for this operation." );
                    filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData };
                }
    
            }
    
            protected void SetCachePolicy( AuthorizationContext filterContext )
            {
                // ** IMPORTANT **
                // Since we're performing authorization at the action level, the authorization code runs
                // after the output caching module. In the worst case this could allow an authorized user
                // to cause the page to be cached, then an unauthorized user would later be served the
                // cached page. We work around this by telling proxies not to cache the sensitive page,
                // then we hook our custom authorization code into the caching mechanism so that we have
                // the final say on whether a page should be served from the cache.
                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
                cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
                cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
            }
    
    
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

If I have an ASP.NET MVC controller action that is called from a jQuery
I have a controller action in ASP.NET MVC that handles uploaded files. However, it
On ASP.net MVC, what is the correct way to have a controller return a
I have an asp.net mvc application with a route similar to: routes.MapRoute(Blog, {controller}/{action}/{year}/{month}/{day}/{friendlyName}, new
My question is as follows: I have a base controller (ASP.Net MVC controller) called
I have an ASP.NET MVC project that works fine on my local machine (no
I have a controller with an action method as follows: public class InventoryController :
I have multiple controller actions that takes an id public ActionResult Get(int? id) {
I have an asp.net mvc2 application that is using StructureMap 2.6 and NHibernate 3.x.
I have a controller action that is being executed by a link that was

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.