我有一个asp.net mvc 4应用程序。有一个类(adminAccess),它有一个方法RestrictAccess来检查用户是否存在于数据库中,如果没有,则返回带有访问被拒绝页面的新HttpForbiddenResult()。
然后我从我的控制器这样调用这个类:
adminAccess access = new adminAccess();
虽然该类初始化正常,但经过一些调试后我发现我的HttpForbiddenResult类中没有调用ExecuteResult,也没有创建ViewResult来向用户显示Access Denied页面。
如果我只是直接在我的控制器的ActionResult中复制我的adminAccess类的内容,一切正常,但我不想在每一页都有这么多的代码。
你能帮我找出问题所在吗?
public class adminAccess
{
string strLoginName = System.Web.HttpContext.Current.User.Identity.Name.ToUpper();
private BookingSystemEntities SystemDB = new BookingSystemEntities();
public object RestrictAccess()
{
try
{
var accessList = SystemDB.Users.SqlQuery("SELECT * FROM dbo.Users where UserLogin = '" + strLoginName + "' and (UserRoleId = 1 or UserRoleId = 2) ").ToList();
foreach (var item in accessList)
{
item.UserLogin.ToString();
if ((item.UserLogin != strLoginName) || (item.UserLogin == null) || (item.UserLogin == string.Empty))
{
return new HttpForbiddenResult();
}
}
if (accessList.Count == 0)
{
// return HttpNotFound();
return new HttpForbiddenResult();
}
}
catch (Exception ex)
{
throw new ApplicationException("Please contact the Helpdesk with the following message :", ex);
}
return RestrictAccess();
}
}
public class HttpForbiddenResult : HttpStatusCodeResult
{
public override void ExecuteResult(ControllerContext context)
{
base.ExecuteResult(context);
// creates the ViewResult adding ViewData and TempData parameters
ViewResult result = new ViewResult
{
ViewName = "AccessDenied",
ViewData = context.Controller.ViewData,
TempData = context.Controller.TempData
};
result.ExecuteResult(context);
}
// calls the base constructor with 403 status code
public HttpForbiddenResult()
: base(HttpStatusCode.Forbidden, "Forbidden")
{
}
}