在LogIn操作方法中从returnurl获取Route值

时间:2013-04-09 12:18:27

标签: c# .net asp.net-mvc asp.net-mvc-3

我有一个看起来像这样的网址

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

returnUrl = "/Event/Details/41"

我需要从return 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和blah blah,只是寻找与MVC相关的解决方案或更简单的东西。

3 个答案:

答案 0 :(得分:2)

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

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 = 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

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:0)

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

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