Search code examples
asp.net-coreasp.net-core-mvcasp.net-core-1.0

Why is cshtml extension required?


I've been using MVC for 2 years and in all this time I never had to use the `.cshtml' extension when referring to views. Now I upgraded to RC2 and started getting "View not found errors". Apart from the pain of adding the extension I now have a lot of code that does not contain the extension.

Is there a way to remove the need for this extension?

PS: I don't know what happened when moving to RC2 but I did not upgrade my project instead created a new one and copied all classes, controllers and views from the old one and fixed the namespaces afterwards.


Solution

  • As Ron C wrote above, its not about ViewResult or PartialViewResult, its about missing the filename extension ".cshtml", when you "viewName" parameter has a relative path value.

    That is how the RazorViewEngine (default implementation of IRazorViewEngine) is working in RC2. You can view the code here.

    A solution could be to override the View and PartialView methods of a BaseController to automatically append ".cshtml" when needed.

    public class BaseController : Controller
    {
        [NonAction]
        public override ViewResult View(string viewName, object model)
        {
            return base.View(AppendRazorFileExtensionIfNeeded(viewName), model);
        }
    
        [NonAction]
        public override PartialViewResult PartialView(string viewName, object model)
        {
            return base.PartialView(AppendRazorFileExtensionIfNeeded(viewName), model);
        }
    
        private string AppendRazorFileExtensionIfNeeded(string viewName)
        {
            // If viewname is not empty or null
            if (!string.IsNullOrEmpty(viewName))
            {
                // If viewname does have a relative path
                if (viewName[0] == '~' || viewName[0] == '/')
                {
                    // If viewname does not have a ".cshtml" extension
                    if (!viewName.EndsWith(".cshtml", StringComparison.OrdinalIgnoreCase))
                    {
                        viewName = string.Concat(viewName, ".cshtml");
                    }
                }
            }
    
            return viewName;
        }
    }