简体   繁体   中英

Get the controller and action name in Controller method with Route attribute

I define a route in controller,

[Route("AboutUs/Profile")]
[Route("AboutUs/Organization")]
public ActionResult Contents()
{
    string _controller = RouteData.Route.GetRouteData(this.HttpContext).Values["controller"].ToString();
    string _action = RouteData.Route.GetRouteData(this.HttpContext).Values["action"].ToString(); 
}

but _action == "Contents" , how can I get _action = "Profile" ?

I tried this:

string _controller = this.ControllerContext.RouteData.Values["controller"].ToString();
string _action = this.ControllerContext.RouteData.Values["action"].ToString();

and this

string _controller = this.RouteData.Values["controller"].ToString();
string _action = this.RouteData.Values["_action"].ToString();

but all of this does not work.

I wrote this code for logging the actions:

public class PreviousPage
{
    public string Action { get; set; }
    public string Controller { get; set; }
    public object Parameters { get; set; }

    public PreviousPage() { PP(); }
    public PreviousPage(string action, string controller, object parameters)
    {
        Action = action;
        Controller = controller;
        Parameters = parameters;
    }

    public void PP()
    {
        var htpc = HttpContext.Current.Request.RequestContext.RouteData.Values;

        object controller;
        htpc.TryGetValue("controller", out controller);
        Controller = controller as string;

        object action;
        htpc.TryGetValue("action", out action);
        Action = action as string;

        object id;
        htpc.TryGetValue("id", out id);
        int q = HttpContext.Current.Request.RawUrl.IndexOf('?');
        if (q>-1)
            Parameters = HttpContext.Current.Request.RawUrl.Substring(q+1);
        else
            Parameters = id as string;
    }
}

It's to mutch but with a bit of modification you'll get there.

Edit:

get the action along a static function:

    public static string GetAction()
    {
        object action=null;
        HttpContext.Current.Request.RequestContext.RouteData.Values.TryGetValue("action", out action);
        return  action as string;
    }

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