我有一个网站,如果用户没有登录,我希望他们被重定向到"登录"页面。用户可以尝试通过发布url来访问网页。我想在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);
}
使用控制器上的[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>
您还有另一个更好的选项,可以在global.asax文件中将AuthorizeAttribute
注册为全局筛选器。
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
....
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}
这样,您只需要将[AllowAnonymous]
应用于希望匿名用户访问的操作。