Dan H
Dan H

Reputation: 1828

Custom ControllerContext

Is there a way to create a custom ControllerContext to wrap the existing ControllerContext in mvc?

Here's what I want to accomplish...

For logging purposes we need to log the controller name, action name, and page name. We get these values from the ControllerContext object right now.

I created a static class, which I'm not very excited about, to get the values for the logging class.

public static class ControllerContextHelper
{
    public static string GetControllerName(ControllerContext context)
    {
        string result = String.Empty;
        if (context.RouteData.Values.ContainsKey("controller"))
        {
            result = context.RouteData.Values["controller"].ToString();
        }
        return result;
    }

    public static string GetActionName(ControllerContext context)
    {
        string result = String.Empty;
        if (context.RouteData.Values.ContainsKey("action"))
        {
            result = context.RouteData.Values["action"].ToString();
        }
        return result;
    }

    public static string GetPageName(ControllerContext context)
    {
        string result = String.Empty;
        if (context.RouteData.Values.ContainsKey("page"))
        {
            result = context.RouteData.Values["page"].ToString();
        }
        return result;
    }
}

I'd much rather have this logic be in the ControllorContext object so i don't need to have a "Helper" class to do it for me.

Upvotes: 3

Views: 1540

Answers (1)

Davor Zlotrg
Davor Zlotrg

Reputation: 6050

You can use extension methods for that

public static class ControllerExtensions
{
    public static string GetControllerName(this ControllerContext context)
    {
        return GetRouteDataValue("controller", context);
    }

    public static string GetActionName(this ControllerContext context)
    {
        return GetRouteDataValue("action", context);
    }

    public static string GetPageName(this ControllerContext context)
    {
        return GetRouteDataValue("page", context);
    }

    private static string GetRouteDataValue(string key, ControllerContext context)
    {
        string value = String.Empty;
        if (context.RouteData.Values.ContainsKey(key))
        {
            value = context.RouteData.Values[key].ToString();
        }
        return value;
    }
}

And in your controller or wherever you have controller available you can call an extension method

public ActionResult Attempt()
{
    var actionName = ControllerContext.GetActionName();
    return View();
}

Upvotes: 3

Related Questions