c# - ASP.NET MVC C# 在类中获取 Controller 和操作名称

标签 c# asp.net-mvc http-get asp.net-mvc-controller

我是 StackOverflow 的新手,所以请原谅我的无知。 :)

我在 Visual Studio 2010 中的 MVC 应用程序(用 C# 编写的 Controller )中遇到了一个小问题。 我想创建一个生成应用程序操作历史记录的方法,为此我想获取每次使用的 Controller 和操作的名称。不幸的是,包含我的 Controller 名称的字符串的第一个字母总是丢失。 我使用了这段代码:

    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();

OwnedContext 的定义如下:

    private class OwnedContext : HttpContextBase
    {
        private readonly HttpRequestBase mockHttpRequestBase;

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

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

Action 名称存储正确,但当我调试此代码时,我看到 controllerName 字符串包含 Controller 的名称,但第一个(大写)字母始终丢失,即使 url 字符串包含具有此模式的值:/ Controller / Action 。

我将不胜感激任何指示、代码示例或为什么会发生这种情况的解释。如果我的描述不准确,请告诉我,我会改进。

提前致谢:)

编辑:找到解决方案:

发现问题(某种程度上):OwnedContext 有问题(在我原来的问题中定义)。起初我按照 HarHaHu 的建议使用了 routeValueDictionary,但最初的问题仍然存在,直到我将 httpContext 作为 GetRouteData 的参数:

    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();

其中 httpContext 有一个自定义的 getter:

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

这样我省略了 OwnedContext 并最终得到了我的 Controller 的全名(例如:Furniture 而不是 urniture)。

感谢您的提示。 :) 希望这对某人有帮助。祝你好运!

最佳答案

var routeValueDictionary = urlHelper.RequestContext.RouteData.Values;

将其与您的自定义上下文一起使用。

关于c# - ASP.NET MVC C# 在类中获取 Controller 和操作名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9573664/

相关文章:

android - 从 Android 应用程序读取 HTML 源代码

c# - 我可以使用流在 SQL Server (C#) 中插入或更新行吗?

c# - 处理 WPF 中的无效图像源

c# - 在 C# 中公开实现绳索?

c# - 计算页数的最简单公式?

asp.net-mvc - 如何在MVC Url.Action中调用不同 Controller 中的不同方法?

c# - 如何使用 Mvc 3 Razor 填充列表?

css - 使用nuget安装时jQuery UI组合包下载在哪里

angular - http.get 似乎没有执行

php - 如何处理通过 HTTP GET 在 PHP 中返回大型 JSON 对象?