我知道在控制器顶部的 MVC 中,您可以使用该[Authorize()]
属性将对该整个控制器的访问限制为某些经过身份验证的用户和/或角色,但不能通过 IP,但这必须在每个控制器实例上完成。有没有办法将整个 MVC 区域的访问限制为经过身份验证的用户/角色或请求源 IP?
user1365911
问问题
4872 次
1 回答
16
在您的区域创建一个基本控制器:
[AuthorizeArea(AllowIpAddresses = new [] {"1.1.1.1", "1.2.3.4"})]
public class CustomAreaBaseController : Controller
{
public CustomAreaBaseController()
{
// possibly any other common code that you want to run for all controllers in this area
}
}
让您所在地区的所有控制器都从基本控制器派生:
public class HomeController : CustomAreaBaseController
{
// actions for this controller
}
创建自定义授权属性:
public class AuthorizeArea : AuthorizeAttribute
{
public string[] AllowIpAddresses { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool isValid = false;
if (httpContext == null)
throw new ArgumentNullException("httpContext");
// get current ip address
var ipAddress = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
ipAddress = httpContext.Request.ServerVariables["remote_host"];
if (AllowIpAddresses.Contains(ipAddress)) isValid = true;
return base.AuthorizeCore(httpContext) && isValid;
}
}
于 2013-08-05T18:03:21.663 回答