我正在使用MVC3 / Razor。登录网站后,它出现在主页上,但我不明白为什么会出现上一页网址。
场景:当我将用户从LogOn页面重定向到主页时,地址栏中的url显示为“http:// localhost:55104 / Account / LogOn”而不是“http:// localhost:55104 / Home / Index “
帐户控制器
// GET: /Account/LogOn
public ActionResult LogOn()
{
if (HttpContext.User.Identity.IsAuthenticated == true)
{
return RedirectToAction("Index", "Home");
}
else
{
return View();
}
}
// POST: /Account/LogOn
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
try
{
if (AppAuthentication.Authenticate(model.UserName, model.Password, "10.0.3.18"))
{
string userName = model.UserName;
var user = new List<String>();
MySqlConnection con = DAL.GetMySqlConnection();
MySqlCommand cmd = new MySqlCommand("SELECT user_id, user_fname FROM users WHERE user_code='" + userName + "' AND user_treeCode <> 'xxx'", con);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
user.Add(rdr.GetString(0));
user.Add(rdr.GetString(1));
}
con.Close();
FormsAuthentication.SetAuthCookie(user[0], model.RememberMe);
Session["userID"] = user[0];
Session["userName"] = user[1];
return RedirectToAction("Index", "Home");
}
else
{
ViewBag.OpenID = "Invalid credentials ";
}
}
catch (Exception ex)
{
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Gloabal.asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
答案 0 :(得分:2)
您的登录表单必须是Ajax表单。在这种情况下,RedirectToAction就像一个View方法。
答案 1 :(得分:0)
你可以这样使用
if (ModelState.IsValid)
{
if (string.IsNullOrEmpty(returnUrl))
{
returnUrl = Url.Action("Index", "App");
}
if (Request.IsAjaxRequest())
{
return Json(new { returnUrl = returnUrl });
}
return Redirect(returnUrl);
}
在视图中:
<% using (Ajax.BeginForm(
"LogOn",
null,
new AjaxOptions {
HttpMethod = "POST",
OnSuccess = "success"
},
new {
id = "SignInForm", ReturnUrl = Request.QueryString["ReturnUrl"]
})) { %>
<<Page HTML Controls>>
<input type="submit" value="Log On" />
<% } %>
<script type="text/javascript">
function success(context) {
var returnUrl = context.get_data().returnUrl;
if (returnUrl) {
window.location.href = returnUrl;
} else {
// TODO: update the target form element with the returned partial html
}
}
</script>