Sco*_*ott 15 c# asp.net-mvc authorization asp.net-mvc-3
如何创建自定义AuthorizeAttribute,以字符串参数的形式指定消息,然后将其传递到登录页面?
例如,理想情况下执行此操作会很酷:
[Authorize(Message = "Access to the blah blah function requires login. Please login or create an account")]
public ActionResult SomeAction()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
然后,在Login操作中,我可以这样做:
public ActionResult Login(string message = "")
{
ViewData.Message = message;
return View();
}
Run Code Online (Sandbox Code Playgroud)
最后在视图中我可以这样做:
@if (!String.IsNullOrEmpty(ViewData.Message))
{
<div class="message">@ViewData.Message</div>
}
<form> blah blah </form>
Run Code Online (Sandbox Code Playgroud)
基本上我想将自定义消息传递到登录页面,以便我可以显示特定于用户在该特定时间尝试访问的消息.
fre*_*nky 23
你可以尝试这样的事情:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public string Message { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
var result = new ViewResult();
result.ViewName = "Login.cshtml"; //this can be a property you don't have to hard code it
result.MasterName = "_Layout.cshtml"; //this can also be a property
result.ViewBag.Message = this.Message;
filterContext.Result = result;
}
Run Code Online (Sandbox Code Playgroud)
用法:
[CustomAuthorize(Message = "You are not authorized.")]
public ActionResult Index()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14738 次 |
| 最近记录: |