我有一个网站,如果用户未登录,我希望在其中将用户重定向到“登录”页面。用户可以尝试通过发布URL来访问网页。我想在C#MVC 4.5中做到这一点
在这里,除非登录,否则我不希望动作“ [Authorize]”可用。这是查看索引页面的索引动作。
//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>
您还有另一个更好的选择,可以AuthorizeAttribute
在global.asax文件中注册为全局过滤器。
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
....
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}
这样,您仅需将应用于[AllowAnonymous]
希望匿名用户访问的操作即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句