返回登录视图,而不是在MVC 2应用重定向(网站宽)
我有一个MVC 2应用程序,每一个页面需要的(除了当前为/帐号/登录)授权,但我更希望,而不是将其转发给“/ Account/LogOn?ReturnUrl =/SomePage”来验证用户,它只是显示登录表单而不是用户请求的页面,所以URL不会改变返回登录视图,而不是在MVC 2应用重定向(网站宽)
我已经有一个BaseController几乎每一个其他控制器继承,我使用的地方,我已经把我的AuthorizeAttribute其他用途(改变了简洁):
[Authorize(Roles = "Role1, Role2")]
public class BaseController : Controller
{
}
我对一个漂亮的解决方案最初的想法是覆盖AuthorizeAttribute类的方式,将是这个样子:
public class AuthorizeWithLoginAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
//This doesn't work obviously
filterContext.Result = View("Logon");
}
}
然后,我可以简单地我上面的控制器更改为:
[AuthorizeWithLogin(Roles = "Role1, Role2")]
public class BaseController : Controller
{
}
是有一种方法可以真正做到这一点? (这是我的第一篇文章仅供参考)
你能不能做一下基本控制器类似
if(!User.Identity.IsInRole("Role1", "Role2")
{
return View("Logon")
}
return;
那么这完全适用于一半!这是非常明显的,谢谢。但是现在我必须弄清楚如何处理来自该页面的表单帖子。我会在一点点再次更新我尝试一些 – 2010-07-12 01:23:31
后顺便说一句......需要修改你的代码: 如果(User.IsInRole(“role1上”)&& User.IsInRole(“role2所”)!) 但我知道你的意思 – 2010-07-12 01:57:49
我不知道如果我要回答我自己的问题,但我想后的解决方案Simon Hazelton的启发。
我BaseController类(为简洁起见再次修改):
[Authorize(Roles = "Role1, Role2")]
public class BaseController : Controller
{
protected override void OnAuthorization(AuthorizationContext filterContext)
{
if (!User.IsInRole("Role1") && !User.IsInRole("Role2"))
{
filterContext.Result = View("LogonView");
}
base.OnAuthorization(filterContext);
}
}
并在视图/Views/Shared/LogonView.aspx形式:
(这是从默认/查看/帐户复制/ LogOn.aspx,与修改Html.BeingForm())
<% using (Html.BeginForm(new { action = "LogOn", controller = "Account", area = "", returnUrl = Request.Url.PathAndQuery }))
<%: Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") %>
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
<%: Html.LabelFor(m => m.UserName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.UserName) %>
<%: Html.ValidationMessageFor(m => m.UserName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Password) %>
</div>
<div class="editor-field">
<%: Html.PasswordFor(m => m.Password) %>
<%: Html.ValidationMessageFor(m => m.Password) %>
</div>
<div class="editor-label">
<%: Html.CheckBoxFor(m => m.RememberMe) %>
<%: Html.LabelFor(m => m.RememberMe) %>
</div>
<p>
<input type="submit" value="Log On" />
</p>
</fieldset>
</div>
<% } %>
我想它做的更好是不是在做不成功的登录原重定向的情况(因为这实际上只是张贴到正常的唯一的事方法)
你的意思是说,而不是重定向到'/帐号/ LogOn支持?RETURNURL =/SomePage'你希望它被重定向到'/帐号/ Logon'仅供autentication? – 2010-07-12 00:36:40
我想完全避免重定向。所以,如果我访问www.mysite.com,我需要进行身份验证,那么它只会告诉我一个登录表单就在那里,不重定向我/帐号/登录在所有...基本上告诉我的登录视图,而不是索引视图(问题作为登录的看法是不同的控制器上) – 2010-07-12 00:39:25