MVC中的跳转问题。。
写了个Controller基类 用来做登录验证。 重写下方法 但跳转不好用。
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (HttpContext.User.Identity.Name == "")
{
Response.Write("4567890-"); //可以输出
RedirectToAction("login", "home"); //不能跳转,不报错
Redirect("~/dome.htm"); ////不能跳转,不报错
Response.Write("<script type=\"text/javascript\"> window.location = \"/dome.htm\"</script>"); //可以跳转
}
}
请问RedirectToAction、Redirect为啥不用用呢。。
我这么做十分用户是否登录的判断是否有问题?
谢谢 MVC
[解决办法]
RedirectToAction("login", "home"); //不能跳转,不报错
只是跳转到Action,所以你必选要先新建Controller(homeController),然后再在Controller里新建视图
public ActionResult login()
{
return view()
}
右键login新建view
[解决办法]
filterContext.Result = new RedirectResult(FormsAuthentication.LoginUrl + "?ReturnUrl=" + filterContext.HttpContext.Request.UrlReferrer);
[解决办法]
试试2楼的的做法。
一般我们做登录检测的话都是用Attribute比较多,这种方式相对来说比较灵活,你可以参考一下。
Attribute定义:
[AttributeUsage(AttributeTargets.Class
[解决办法]
AttributeTargets.Method
[解决办法]
AttributeTargets.Property, AllowMultiple = false)]
public class LoginOnVerificationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext) {
base.OnActionExecuting(filterContext);
if (string.IsNullOrEmpty(HttpContext.User.Identity.Name)) {
string target = HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.ToString());
filterContext.Result = new RedirectResult(string.Format("http://www.yourdomain.com/memberlogin.aspx?target={0}", target));
}
}
}
Attribute的使用:
[LoginOnVerification]
public class GalleryController : Controller {
// your codes.
}
也可以用于方法:
[LoginOnVerification]
public ActionResult Download() {
// your codes.
}