从登录操作方法中的returnnurl获取路由值

本文关键字:获取 路由 returnnurl 登录 操作方法 | 更新日期: 2023-09-27 18:08:08

我有一个像这样的url

http://mysite/account/login?returnurl=/Event/Details/41

returnUrl = "/Event/Details/41"

我需要从返回url中获取路由值-其中包括EventID = 41

我可以使用以下代码获得事件Id:

public ActionResult Login()
{
   ....
   string returnUrl = Request.QueryString["ReturnUrl"];
   int lastIndex = returnUrl.LastIndexOf("/") + 1;
   string strEventID = returnUrl.Substring(lastIndex);
   int EventID = Int32.Parse(strEventID);
   ....
}

但我觉得可能有一个更灵活的方式,可以让我访问查询字符串,路由值等,而不用手动这样做。

我不想使用WebRequest, WebClient等,只是寻找MVC相关的解决方案或更简单的东西。

从登录操作方法中的returnnurl获取路由值

为了访问查询字符串,您可以直接将它们放在动作签名中:

public ActionResult Login(string returnurl)
{
   ....
   if(!string.IsNullOrWhiteSpace(returnurl)) {
       int lastIndex = returnurl.LastIndexOf("/") + 1;
       string strEventID = returnUrl.Substring(lastIndex);
       int EventID = Int32.Parse(strEventID);
   }
   ....
}

编辑:

为了从returnurl中提取路由参数,您可以通过regex解析它:

Regex regex = new Regex("^/(?<Controller>[^/]*)(/(?<Action>[^/]*)(/(?<id>[^?]*)('?(?<QueryString>.*))?)?)?$");
Match match = regex.Match(returnurl);
// match.Groups["Controller"].Value is the controller, 
// match.Groups["Action"].Value is the action,
// match.Groups["id"].Value is the id
// match.Groups["QueryString"].Value are the other parameters

try this:

public ActionResult Login(string returnUrl)
{
   ....
   var id = this.GetIdInReturnUrl(returnUrl);
   if (id != null) 
   {
   }
   ....
}
private int? GetIdInReturnUrl(string returnUrl) 
{
   if (!string.IsNullOrWhiteSpace(returnUrl)) 
   {
       var returnUrlPart = returnUrl.Split('/');
       if (returnUrl.Length > 1) 
       {
           var value = returnUrl[returnUrl.Length - 1];
           int numberId;
           if (Int32.TryParse(value, out numberId))
           {
               return numberId; 
           }
       }
   }
   return (int?)null;
}

在模型绑定阶段将控制器动作更改为此动作。. NET MVC查看请求并找到returnUrl的值,您不需要手动处理它。

    public ActionResult Login(string returnUrl)
    {
        int EventID = 0;
        int.TryParse(Regex.Match(returnUrl, "[^/]+$").ToString(), out EventID);
        ....
    }