如果经过身份验证,MVC 中的不同默认页面
Different default page in MVC if authenticated
这可能是一个非常简单的问题,但我很难理解 MVC 路由。
场景:用户通过在浏览器中输入www.mydomain.com进入我的网站。我想根据用户是否经过身份验证重定向到不同的默认页面。
我当前的身份验证方法:在 Application_PostAuthenticateRequest 中,我检查 FormsAuthentication cookie。如果找到我从 cookie 中解析用户主体。
我应该在哪里以及如何配置重定向?
我不确定你问题的第二部分到底是什么意思,但是,你问题的主要部分应该非常简单。这与 "routing" 无关,只是当有人访问您站点的索引(根)页面时您想发生的事情。
假设这是您的 controller/action
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult AuthenticatedIndex()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
要测试某人是否在 controller/action 中通过身份验证,您可以使用这行代码:
User.Identity.IsAuthenticated
哪个 returns true/false 取决于用户是否已通过身份验证。接下来,如果用户通过了身份验证,我们需要将其发送到其他地方。这是通过使用以下内容完成的:
RedirectToAction("actionName", "controllerName");
因此,如果我们将所有这些结合在一起,我们现在可以更新我们的 Index()
方法,并在用户通过身份验证后将其发送到其他地方。
public ActionResult Index()
{
if(User.Identity.IsAuthenticated){
//send them to the AuthenticatedIndex page instead of the index page
return RedirectToAction("AuthenticatedIndex", "Home");
}
return View();
}
我在这里看到的唯一警告是登录用户将永远无法访问 Index 方法,这可能是您想要的。
这可能是一个非常简单的问题,但我很难理解 MVC 路由。
场景:用户通过在浏览器中输入www.mydomain.com进入我的网站。我想根据用户是否经过身份验证重定向到不同的默认页面。
我当前的身份验证方法:在 Application_PostAuthenticateRequest 中,我检查 FormsAuthentication cookie。如果找到我从 cookie 中解析用户主体。
我应该在哪里以及如何配置重定向?
我不确定你问题的第二部分到底是什么意思,但是,你问题的主要部分应该非常简单。这与 "routing" 无关,只是当有人访问您站点的索引(根)页面时您想发生的事情。
假设这是您的 controller/action
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult AuthenticatedIndex()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
要测试某人是否在 controller/action 中通过身份验证,您可以使用这行代码:
User.Identity.IsAuthenticated
哪个 returns true/false 取决于用户是否已通过身份验证。接下来,如果用户通过了身份验证,我们需要将其发送到其他地方。这是通过使用以下内容完成的:
RedirectToAction("actionName", "controllerName");
因此,如果我们将所有这些结合在一起,我们现在可以更新我们的 Index()
方法,并在用户通过身份验证后将其发送到其他地方。
public ActionResult Index()
{
if(User.Identity.IsAuthenticated){
//send them to the AuthenticatedIndex page instead of the index page
return RedirectToAction("AuthenticatedIndex", "Home");
}
return View();
}
我在这里看到的唯一警告是登录用户将永远无法访问 Index 方法,这可能是您想要的。