ASP.NET MVC C# Get controller and action name in c

2019-04-30 12:31发布

问题:

I'm pretty much new to StackOverflow so please forgive any signs of my ignorance. :)

I have a somewhat minor issue with an MVC application in Visual Studio 2010 (Controllers written in C#). I want to create a method which generates an application action history and for that purpose I want to get the name of the controller and action that are used each time. Unfortunately the first letter of the string which holds my controller name is always missing. I used this code:

    string url = HttpContext.Current.Request.RawUrl;
    RouteData route = RouteTable.Routes.GetRouteData(new OwnedContext(url));
    var values = route.Values;
    string controllerName = values["controller"].ToString();
    string actionName = values["action"].ToString();

Where OwnedContext is defined like this:

    private class OwnedContext : HttpContextBase
    {
        private readonly HttpRequestBase mockHttpRequestBase;

        public OwnedContext(string appRelativeUrl)
        {
            this.mockHttpRequestBase = new OwnedRequest(appRelativeUrl);
        }

        public override HttpRequestBase Request
        {
            get { return mockHttpRequestBase; }
        }
    }

The action name is stored correctly but when i debug this code i see that the controllerName string holds the name of the controller but the first (Capital) letter is always missing, even though the url string holds a value with this pattern: /controller/action.

I will appreciate any pointers, code examples or an explanation why this happens. If my description is not accurate let me know, I will improve it.

Thanks in advance :)

EDIT: SOLUTION FOUND:

Found the problem (sort of): There was something wrong with OwnedContext (defined in my original question). At first I used routeValueDictionary as HarHaHu suggested but the original problem persisted, until I placed httpContext as GetRouteData's parameter:

    string url = HttpContext.Current.Request.RawUrl;
    RouteData route = RouteTable.Routes.GetRouteData(httpContext);
    UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContext, route));

    var routeValueDictionary = urlHelper.RequestContext.RouteData.Values;
    string controllerName = routeValueDictionary["controller"].ToString();
    string actionName = routeValueDictionary["action"].ToString();

Where httpContext has a custom getter:

    public new HttpContextBase httpContext
    {
        get
        {
            HttpContextWrapper context =
                new HttpContextWrapper(System.Web.HttpContext.Current);
            return (HttpContextBase)context;
        }
    }

This way I omitted the OwnedContext and finally got my controller's full name (for example: Furniture and not urniture).

Thanks for the tips. :) Hope this helps someone. Good luck!

回答1:

var routeValueDictionary = urlHelper.RequestContext.RouteData.Values;

use this with your custom context.