Can I get the controller from the HttpContext?

前端 未结 4 1143
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 01:35

Given an HttpContext (or HttpContextBase), is there a way to get an instance of the Controller?

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 02:08

    For those looking just to get the controller name and not an actual instance, as is needed for custom authorization overrides of AuthorizeCore(httpContext), this is the clean code.

    var request = httpContext.Request;
    var currentUser = httpContext.User.Identity.Name;
    string controller = request.RequestContext.RouteData.Values["controller"].ToString();
    string action = request.RequestContext.RouteData.Values["action"].ToString();
    

提交回复
热议问题