简体   繁体   中英

Get Name of Controller from ActionFilter

I'm writing an ActionFilter and would like to have a more type-safe way to use RedirectToRouteResult. While investigating this, I wondered if there was a way to get the name (as a string) of any of my controllers. So for example, I would like to get "Home" from my HomeController, or "Admin" from my Admin controller. Is this at all possible?

From a filter context you can get the controller name by using:

public class MyFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext filterContext)
    {
        //That will give you "HomeController"
        var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

        //You can remove the "Controller" part, by replacing it with an empty string, like:
        var justTheController = controllerName.Replace("Controller", string.Empty);
    }
}

Have you tried this. You know you can substitute typeof by GetType on instance variable. if you have HomeController instance homeCtrl....you can do homeCtrl.GetType

  var fullName= typeof(HomeController).Name;
  var partialName = fullName.Remove(fullName.IndexOf("Controller"));

Actually there are ways to get the controller name :

  1. filterContext.Controller will give you an object from where you can deduce the controller name as filterContext.Controller.GetType().Name
  2. You always have the controller in the route values and can deduce as Request.RequestContext.RouteData.Values("controller").ToString()

Write extension method

public static class ControllerStringExtension
{
    private const string ControllerString = "Controller";
    public static string Short(this string value)
    {
        if (value.EndsWith(ControllerString))
        {   
            //Remove 'Controller' from end of value name.             
            return value.Remove(value.Length - ControllerString.Length);
        }
        throw new ApplicationException("Should be used only for Controller names.");
    }
}

than use: Redirect to 'home' controler and 'index' action.

 public RedirectToRouteResult Something()
    {
        return RedirectToAction(nameof(HomeController.Index), nameof(HomeController).Short());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM