1-您可以继承[AuthorizeAttribute]
并自定义实现以路由到所需的未经授权的页面。
看到选定的 awnser 是这个问题:
Redirecting authorized controller in ASP.NET MVC
2-如果您从 ajax 调用(即$.Get(url)
或$("#somediv").Load(url)
)加载部分,请确保调用的操作url
正确地用您的自定义装饰[AuthorizeAttribute]
。
否则,您将需要在剃刀视图中使用一些逻辑来检查用户是否经过身份验证。类似的东西
@if (User.Identity.IsAuthenticated)
{
// Normal case
}
else
{
@Html.Partial("Login")
}
您的登录部分将显示所需的登录视图。
更新
您可以实现 2 个不同的属性,每个场景一个。
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
public class IsUserAdminAttribute : CustomAuthorizedBaseAttribute
{
// Custom logic to redirect to admin logon partial/view
...
}
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
public class IsAuthenticatedAttribute : CustomAuthorizedBaseAttribute
{
// Custom logic to redirect to basic/comment logon partial/view
...
}
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
public abstract class CustomAuthorizedBaseAttribute : AuthorizeAttirbute
{
// Shared custom logic implementation
...
}
您可以根据场景使用其中一种来装饰您的控制器操作。