33
44using System ;
55using System . IO ;
6+ using System . Linq ;
67using System . Threading . Tasks ;
78using Microsoft . AspNetCore . Http ;
89using Microsoft . AspNetCore . Mvc ;
910using Microsoft . AspNetCore . Mvc . Abstractions ;
1011using Microsoft . AspNetCore . Mvc . ModelBinding ;
1112using Microsoft . AspNetCore . Mvc . Razor ;
1213using Microsoft . AspNetCore . Mvc . Rendering ;
14+ using Microsoft . AspNetCore . Mvc . ViewEngines ;
1315using Microsoft . AspNetCore . Mvc . ViewFeatures ;
1416using Microsoft . AspNetCore . Routing ;
1517
@@ -31,18 +33,10 @@ public RazorViewToStringRenderer(
3133 _serviceProvider = serviceProvider ;
3234 }
3335
34- public async Task < string > RenderViewToStringAsync < TModel > ( string name , TModel model )
36+ public async Task < string > RenderViewToStringAsync < TModel > ( string viewName , TModel model )
3537 {
3638 var actionContext = GetActionContext ( ) ;
37-
38- var viewEngineResult = _viewEngine . FindView ( actionContext , name , false ) ;
39-
40- if ( ! viewEngineResult . Success )
41- {
42- throw new InvalidOperationException ( string . Format ( "Couldn't find view '{0}'" , name ) ) ;
43- }
44-
45- var view = viewEngineResult . View ;
39+ var view = FindView ( actionContext , viewName ) ;
4640
4741 using ( var output = new StringWriter ( ) )
4842 {
@@ -67,6 +61,28 @@ public async Task<string> RenderViewToStringAsync<TModel>(string name, TModel mo
6761 }
6862 }
6963
64+ private IView FindView ( ActionContext actionContext , string viewName )
65+ {
66+ var getViewResult = _viewEngine . GetView ( executingFilePath : null , viewPath : viewName , isMainPage : true ) ;
67+ if ( getViewResult . Success )
68+ {
69+ return getViewResult . View ;
70+ }
71+
72+ var findViewResult = _viewEngine . FindView ( actionContext , viewName , isMainPage : true ) ;
73+ if ( findViewResult . Success )
74+ {
75+ return findViewResult . View ;
76+ }
77+
78+ var searchedLocations = getViewResult . SearchedLocations . Concat ( findViewResult . SearchedLocations ) ;
79+ var errorMessage = string . Join (
80+ Environment . NewLine ,
81+ new [ ] { $ "Unable to find view '{ viewName } '. The following locations were searched:" } . Concat ( searchedLocations ) ) ; ;
82+
83+ throw new InvalidOperationException ( errorMessage ) ;
84+ }
85+
7086 private ActionContext GetActionContext ( )
7187 {
7288 var httpContext = new DefaultHttpContext ( ) ;
0 commit comments