Working with IViewLocationExpander in mvc

前端 未结 2 1434
梦如初夏
梦如初夏 2020-12-19 10:37

I want to render views from a custom location, so for that I have implemented the IViewLocationExpander interface in a class. I have registered the same class

相关标签:
2条回答
  • 2020-12-19 11:18

    If you're trying to get Razor to locate views from another location, I've used in this technique in the past. ReSharper is also smart enough to pick up on that.

    0 讨论(0)
  • 2020-12-19 11:31

    PopulateValues exists as a way to specify parameters that your view lookup would vary by on a per-request basis. Since you're not populating it, the view engine uses cached values from an earlier request.

    To solve this, add your ApplicationType variable to the PopulateValues() method and the ExpandValues() method should get called whenever that value changes:

    public class CustomViewLocationExpander : IViewLocationExpander
    {
        public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
        {
            string folderName = context.Values["ApplicationType"];
            viewLocations = viewLocations.Select(f => f.Replace("/Views/", "/" + folderName + "/"));
    
            return viewLocations;
        }
    
        public void PopulateValues(ViewLocationExpanderContext context)
        {
            var session = context.ActionContext.HttpContext.RequestServices.GetRequiredService<SessionServices>();
            string applicationType = session.GetSession<string>("ApplicationType");
            context.Values["ApplicationType"] = applicationType;
        }
    }
    
    0 讨论(0)
提交回复
热议问题