Logo
技术 C#

Mvc校验用户没有登录就跳转的实现

photo
Pastore Antonio

2022年05月27日

看字面意思很简单,就是判断用户是否登录了,如果没有登录就跳转到登陆页面。

没错,主要代码如下(这里就不写判断登录了,直接跳转)

首先在控制器中新建一个BaseController

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        //这里判断出没有登录然后进行跳转
        Response.Redirect("/Login/Index");
 }}

public class TestController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }
}

那么至此,大功告成!

可是如果你真的这么干了,我会毫不夸张的告诉你,你死定了!一点不吓人的告诉你

为什么呢?

原因很简单:断点调试发现一个严重的问题,在执行完下列代码之后

//这里判断出没有登录然后进行跳转
Response.Redirect("/Role/Index");

直至将Test控制器下的Index方法执行完毕,才在浏览器中显示了/Login/Index页面。

解决方法:

在跳转的时候,不用Response.Redirect进行跳转

而是将ActionExecutingContextResult属性赋值为我们要跳转的地址就OK了!

如下:

filterContext.Result = new RedirectResult("/Login/Index");

本文为原创文章,请注意保留出处!
修复群晖Synology Drive client右键菜单缺失问题 Local, clean & environmental 作者:Pastore Antonio
1806 浏览量
1779 浏览量
configure: error: Package requirements (oniguruma) were not met Local, clean & environmental 作者:Pastore Antonio
1524 浏览量
Adobe Acrobat Pro 激活 Local, clean & environmental 作者:Pastore Antonio
1519 浏览量
追寻日出,找回自己 Local, clean & environmental 作者:Pastore Antonio
1488 浏览量