简体   繁体   中英

Razor View Race Condition

In a custom razor engine, derived from RazorViewEngine, I've spotted what I think is unstable code:

    public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
    {
        ViewLocationFormats = AddViewDynamicFormat(controllerContext, viewName).ToArray();
        AreaViewLocationFormats = AddAreaViewDynamicFormat(controllerContext, viewName).ToArray();
        return base.FindView(controllerContext, viewName, masterName, useCache);
    }

My concern is that when two requests are being processed "at the same time," the first will set the location formats as it needs, but before it can use them - the second threaded request might have a chance to set the location formats a different way. The rest gets ugly.

Is this a valid concern? Said differently, does ASP.NET MVC guarantee that the Razor View engine will handle exactly one request at a time? I doubt that is the case.

Likewise, if there was one razor view engine object per request, then this would be ok. But I also don't believe that is the case.

UPDATE I have confirmed that this is a race condition. I have also found an article showing a dynamic expansive razor search example , which solves the problem without a race condition (though I still wonder if it has a caching issue).

Are ViewLocationFormats and AreaViewLocationFormats virtual? If so, you can put that value in the HttpContext.Current.Items collection and retrieve it from the overridden properties.

I'm nearly positive that the RazorViewEngine isn't meant to be modified at run-time, but merely configured in Global.asax Application_Start. I believe the RazorViewEngine instance exists for the life of the App Domain after startup.

If you need to add additional ViewLocationFormats or AreaViewLocationFormats do it in Application_Start. Application_Start is guaranteed to run only once per App Domain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM