2015-04-22 106 views
0

我已经继承了MVC应用程序,并且作为顽固的Web表单人员,我挣扎着! 我有一个登录控制器可通过https://www.myapp.co.uk/Login/Login 有一个伴随它的模型。所以,我有...在登录控制器中读取ReturnUrl(QueryString值)

using System.ComponentModel.DataAnnotations; 
namespace MyApp.Models 
{ 
    public class LoginModel 
    { 
     [Required] 
     [DataType(DataType.Text)] 
     [MaxLength(50)] 
     [Display(Name = "Username")] 
     public string Username { get; set; } 

     [Required] 
     [DataType(DataType.Password)] 
     [MaxLength(50)] 
     [Display(Name = "Password")] 
     public string Password { get; set; } 

     [Display(Name = "Remember Me?")] 
     public bool RememberMe { get; set; } 
    } 
} 

和控制器......

[HttpPost] 
public ActionResult Login(Models.LoginModel u) 
{ 
    if (ModelState.IsValid) 
    { 
     ClaimsPrincipal cp = MyApp.Identity.Authentication.AuthenticateUser(u.Username, u.Password); 
     if (cp != null) 
     { 
      // process claims here 
      // Check ReturnUrl, and if a valid local URL, redirect there, otherwise use 
      // return RedirectToAction("SomeMethod", "SomeController"); 
     } 
     else 
     { 
      Thread.Sleep(3000); 
      ModelState.AddModelError("BadUserPass", "Login data is incorrect!"); 
     } 
    } 
    return View(u); 
} 

假设URL是这样的:https://www.myapp.co.uk/Login/Login?ReturnUrl=/SomeController/SomeMethod?someVal=123

任何人都可以请告知如何处理的请求后,我可以检查ReturnUrl查询字符串部分是否存在,是否也是本地URL,如果是,则重定向到那里而不是当前控制器?我在控制器中尝试了Request.QueryString["ReturnUrl"],但该值始终为NULL。

回答

1

returnUrl添加为控制器操作的参数。

public ActionResult Login(Models.LoginModel u, string returnUrl) 

的UrlHelper类有检查的URL是否是本地的方法,所以后来这纯粹是这样的:

if (Url.IsLocalUrl(returnUrl)) 
return Redirect(returnUrl); 

// Or whatever your default action is 
return RedirectToAction("Index", "Home", new { area = "" }); 

如果创建窗体身份验证模板创建一个新的MVC项目,这代码将在帐户控制器中作为示例。

+0

查询字符串(!)的查询字符串是否可以“https://www.myapp.co.uk/Login/Login?ReturnUrl =/SomeController/SomeMethod?someVal = 123”的123值将被解析?重定向(returnUrl)完美地工作,所以我不知道我甚至需要打扰。刚刚在这里做了一些*最佳练习*! – EvilDr

+0

@EvilDr,我刚刚测试过,它应该可以正常工作。它看起来只关心问号的第一个实例,后面的任何东西都被视为值的一部分。 – Brandon