3
3
4
4
using System ;
5
5
using System . IO ;
6
+ using System . Linq ;
6
7
using System . Threading . Tasks ;
7
8
using Microsoft . AspNetCore . Http ;
8
9
using Microsoft . AspNetCore . Mvc ;
9
10
using Microsoft . AspNetCore . Mvc . Abstractions ;
10
11
using Microsoft . AspNetCore . Mvc . ModelBinding ;
11
12
using Microsoft . AspNetCore . Mvc . Razor ;
12
13
using Microsoft . AspNetCore . Mvc . Rendering ;
14
+ using Microsoft . AspNetCore . Mvc . ViewEngines ;
13
15
using Microsoft . AspNetCore . Mvc . ViewFeatures ;
14
16
using Microsoft . AspNetCore . Routing ;
15
17
@@ -31,18 +33,10 @@ public RazorViewToStringRenderer(
31
33
_serviceProvider = serviceProvider ;
32
34
}
33
35
34
- public async Task < string > RenderViewToStringAsync < TModel > ( string name , TModel model )
36
+ public async Task < string > RenderViewToStringAsync < TModel > ( string viewName , TModel model )
35
37
{
36
38
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 ) ;
46
40
47
41
using ( var output = new StringWriter ( ) )
48
42
{
@@ -67,6 +61,28 @@ public async Task<string> RenderViewToStringAsync<TModel>(string name, TModel mo
67
61
}
68
62
}
69
63
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
+
70
86
private ActionContext GetActionContext ( )
71
87
{
72
88
var httpContext = new DefaultHttpContext ( ) ;
0 commit comments