gpt4 book ai didi

c# - 使用 Route 属性在 Controller 方法中获取 Controller 和操作名称

转载 作者:行者123 更新时间:2023-11-30 18:19:16 24 4
gpt4 key购买 nike

我在 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();
}

但是 _action == "Contents",我怎样才能得到 _action = "Profile"

我试过这个:

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

还有这个

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

但这一切都不起作用。

最佳答案

我写了这段代码来记录操作:

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;
}
}

这太过分了,但稍加修改就可以了。

编辑:

通过静态函数获取 Action :

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

关于c# - 使用 Route 属性在 Controller 方法中获取 Controller 和操作名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39455332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com