1

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?

2
  • Its not clear why you want that - you just return the view in the method if ModelState is invalid to display validation errors. Commented Apr 6, 2018 at 7:13
  • I do not want to call the action method and do the check of the ModelState in every action method. I want to check it globally in the action filter. Commented Apr 6, 2018 at 7:22

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.