Unable to get webApi result in controller

纵然是瞬间 提交于 2020-08-11 18:49:28

问题


I am trying to create constraint for route.Based on the access info retrieved from Db,i will choose which route to choose. I have created controller inheriting IRouteConstraint and calling repository,but Unable to get result from httpclient call.

Code snippet of my 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") }
              );

Code snippet of 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;
    }
}
  

the repository is calling httpwrapper class to get result from 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;
    }

Not sure whats the issue,not getting result response = await client.GetAsync(path);.

I am able to get result with the same api and parameters when called from Session_Start event in Global.asax. Please let me know whats the issue and how can retrieve result from http.


回答1:


I have resolved this issue by keeping the route config as it is. Created a new Action filter and reroute the url based on access. Placed this filter on the top of default route.

 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);
    }
}


来源:https://stackoverflow.com/questions/62523482/unable-to-get-webapi-result-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!