我有一个网站,我希望用户在未登录的情况下被重定向到“登录”页面。用户可以尝试通过发布网址来访问该网页。我想在 C# MVC 4.5 中执行此操作
在这里,除非登录,否则我不希望“[授权]”操作可用。 查看索引页是索引操作。
//Login Controller
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection frm)
{
....//other code
}
[Authorize]
public ActionResult Index()
{
List<DTO> obj = objConfigurator.GetDataList();
return View(obj);
}
public ActionResult Edit(int Id)
{
DTO obj = objC.GetListById(Id);
return View(obj);
}
最佳答案
使用 Controller 上的[Authorize]
属性。
[Authorize]
public class YourController: Controller
{
. . .
[AllowAnonymous]
public ActionResult Register()
{
}
[AllowAnonymous]
public ActionResult LogIn()
{
}
. . .
}
此外,您必须在 web.config 中添加登录页面 -
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Login" timeout="2880" />
</authentication>
</system.web>
您还有另一个甚至更好的选择,将 AuthorizeAttribute
注册为 global.asax 文件中的全局过滤器。
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
....
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}
这样,您只需将[AllowAnonymous]
应用于您希望匿名用户访问的操作。
关于asp.net-mvc-4 - 如果用户尝试通过 URL 访问其他网站页面,如何在 C# MVC 4.5 中重定向已登录或未登录到登录页面的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28825324/