How can I get the full view path of the current rendered view in ActionFilterAttribute? I can not find a solutions.
I just want to do some stuff in OnActionExecuted (custom validation ect.) and if the validation fails, I want to display the calling site with the validation error(s) - it seemed simple to me, but it is not, because I cannot find the full path of the latest rendered view ...
So far it workds on OnActionExecuted with this code for a hard-coded view.
filterContext.Result = new ViewResult() {
ViewName = "~/Views/Login/Index.cshtml", // This is the path of the view with the calling form
ViewData = new ViewDataDictionary(filterContext.Controller.ViewData) {
Model = ApplicationFiler.GetViewModel(filterContext)
}
};
So far I thought I could get the full path of the latest rendered view in the context, but I can't. How can I get the full path that really was rendered?
Then I thought, maybe I can get the information after the execution of the action in OnActionExecuted to save the path temporary and use it later. But still I am not able to find the full path (I need the full path of the view which was returned on the last Action execution without any errors).
Do I really have to temporary save the full path on every action that was executed?
You could access View path from action filter in the following way:
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
ViewResult viewResult = filterContext.Result as ViewResult;
RazorView view = viewResult?.View as RazorView;
string viewPath = view?.ViewPath;
// ...
}
You should be ready that ViewResult
is not the only possible ActionResult
returned by controller. Controller could return other action results (e.g. HttpNotFoundResult
or JsonResult
). In this case obviously no view could be accessed in action filter. Construct filterContext.Result as ViewResult
will return null
.