ASP.NET MVC - Optionally Redirect from a Base Class Method?

Mike Hofer

Consider the following block of code that reappears in many of my controller actions. (I'm chiefly concerned with the first 6 lines of the method body).

[HttpGet]
public ActionResult OptOut()
{
    var user = this.SecurityPrincipal;
    if (user.IsReadOnlyUser)
    {
        this.TempData["ViewModel"] = new AuthorizationModel { User = user };
        return this.RedirectToAction("NotAuthorized", "Authorization");
    }

    var model = /* Elided for brevity */

    return this.View(model);
}

My controllers derive from a base class, SecuredController which, in turn, derives from Controller. SecurityPrincipal is a property of SecuredController, and contains extensive Active Directory data about the current user.

In an effort to eliminate duplicate code, I'd ideally like to move the functionality contained in the if {...} block into a base class method, but I can't think of any way to do so, since the return type of the method would have to be ActionResult, resulting in something ungainly like this:

if ((var result = this.RequireReadWrite()) != null)
{
    return result;
}

Can anyone suggest a way to do this, or am I simply out of luck here?

QuantumHive

As mentioned in the comments, especially noting that security is a cross cutting concern we've suggested using MVC Action Filters to be applied in your use case and design.
Microsoft's documentation is pretty informative and there are more examples that can be found on the web on how to use MVC Filters. I'll try to provide an example, but this will be based on a lot of assumptions on your software architecture, since I simply don't have the knowledge of that.

You could create the following class:

public class SecuredFilterAttribute : AuthorizeAttribute
{
    ...
}

If using a Dependency Injection framework, you could inject the SecurityPrincipal service. But again I don't know the architecture of your application, so it's up to you how you create that dependency.
When overriding the AuthorizeCore, you could implement it like so:

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    return !this.SecurityPrinciple.IsReadOnlyUser;
}

And when not authorized override the HandleUnauthorizedRequest method to redirect:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    var redirectRoute = ...; //your route to redirect to an unauthorized page
    filterContext.Result = new RedirectToRouteResult(redirectRoute);
    //do some other things, for example, setting some tempdata information
}

Again it's up to you on how you would use this Filter. You could register it globally, or apply it on a per controller or action basis. To register it globally, in your startup:

GlobalFilters.Filters.Add(new SecuredFilterAttribute());

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Redirect to a Controller from class method in ASP.NET MVC

asp.net MVC Redirect actions from inherited controllers to generic base controller views

Redirect to page OnActionExecuting method ASP.NET Core 5 MVC

ASP.NET MVC - How do I Call a Controller Method from within a View to Redirect to Multiple Other Views?

Redirect to error page from ajax call in ASP.net MVC

Redirect to external URI from ASP.NET MVC controller

ASP.NET MVC Redirect Partial View Request If it is not from a View

ASP.NET MVC 5 - redirect from view only once

ASP.NET Response Redirect of URL Error; from static method

asp.net core route values to base controller and optionally override actions

Porting a class implementation from asp.net mvc to asp.net mvc core

Call an action method from layout in ASP.NET MVC

ASP.NET MVC Return Model From View To Action Method

Redirect to an action method of type HttpPost in ASP.NET Core 5 MVC

Set session in ASP.Net MVC Controller from another class

Inject data from database to a class with ASP.NET MVC Core

Redirect to HTTPS Error - ASP.NET MVC

Redirect() vs RedirectPermanent() in ASP.NET MVC

Redirect Error in ASP.NET MVC 5

Cant do redirect (ASP.NET MVC)

Using javascript to redirect Asp.net MVC

ASP.net Core, redirect to Index method with error message from another method

Optionally static class method for interface compatibility

ASP.NET MVC redirect to action Redirect Loops

ASP MVC redirect to error page from controller

Redirect to new page from Server for ASP.Net MVC Ajax Request

Unable to redirect to an external website from an iframe using Asp.net mvc

How to redirect to root controller action method from an area controller in .net core mvc application?

Built-in base class for controllers in ASP.NET MVC: Controller or ControllerBase?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive