我正在尝试为路线创建约束。基于从Db检索的访问信息,我将选择要选择的路线。 我已经创建了继承IRouteConstraint并调用存储库的控制器,但是无法从httpclient调用中获取结果。
我的routeConfig的代码段
routes.MapRoute(
name: "Home",
url: "{*routelink}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { routelink = new UserAccessController("Home") }
);
routes.MapRoute(
name: "Reports",
url: "{*routelink}",
defaults: new { controller = "Reports", action = "Index" },
constraints: new { routelink = new UserAccessController("Reports") }
);
Constarint的代码段
public class UserAccessController : IRouteConstraint
{
// GET: UserAccess
private readonly string _controller;
public UserAccessController(string Controller)
{
_controller = Controller;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
bool _authorized = false;
var userAccessDetails = GetUserRoleDetails();
switch (_controller)
{
case "Home":
{
_authorized = Convert.ToBoolean(userAccessDetails.CanAccessHome);
return _authorized;
}
case "Reports":
{
_authorized = Convert.ToBoolean(userAccessDetails.Result.CanAccessReports);
return _authorized;
}
}
return _authorized;
}
public async Task<UserRole> GetUserRoleDetails()
{
IRepository _repository = new Repository();
var userRoleDetails = new UserRole();
var currentUser = await _repository.GetCurrentUser(Path.GetFileName(HttpContext.Current.User.Identity.Name.ToUpper()));
if (currentUser != null)
{
var roles = await _repository.GetUserRoles();
userRoleDetails = roles.Where(r => r.RoleId == currentUser.RoleId).FirstOrDefault();
}
return userRoleDetails;
}
}
存储库正在调用httpwrapper类以从httpclient获取结果。
public static async Task<IEnumerable<T>> GetAsync(IEnumerable<T> t, string path)
{
HttpResponseMessage response;
response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
t = await response.Content.ReadAsAsync<IEnumerable<T>>();
}
return t;
}
不确定是什么问题,未获得结果 response = await client.GetAsync(path);
。
从Global.asax中的Session_Start
事件中调用时,我可以使用相同的api和参数获得结果。请让我知道问题出在哪里,以及如何从http中检索结果。
答案 0 :(得分:0)
我通过保留路由配置来解决此问题。 创建了一个新的动作过滤器,并根据访问权限重新路由了该网址。 将此过滤器放在默认路由的顶部。
public class StartupFilter:ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var userAccessDetails = HttpContext.Current.Session["Role"] as UserRole;
if (userAccessDetails.HasAccessHome)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new
{
controller = "Home",
action = "Index"
}));
}
else if (userAccessDetails.HasAccessReport))
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(
new
{
controller = "Reports",
action = "Index"
}));
}
base.OnActionExecuting(filterContext);
}
}