使用Asp.Net,很容易看到Razor View Engine生成的代码:添加编译错误,错误页面将提供对Razor页面源的访问.
解决方法
将以下类添加到ASP.NET Core MVC项目中:
using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.Razor.Compilation; using Microsoft.AspNetCore.Mvc.Razor.Internal; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; public class CustomCompilationService : DefaultRoslynCompilationService,ICompilationService { public CustomCompilationService(ApplicationPartManager partManager,IOptions<RazorViewEngineOptions> optionsAccessor,IRazorViewEngineFileProviderAccessor fileProviderAccessor,ILoggerFactory loggerFactory) : base(partManager,optionsAccessor,fileProviderAccessor,loggerFactory) { } CompilationResult ICompilationService.Compile(RelativeFileInfo fileInfo,string compilationContent) { return base.Compile(fileInfo,compilationContent); } }
使用上面的类重写MVC添加的ICompilationService;
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSingleton<ICompilationService,CustomCompilationService>(); }
在CustomCompilationService的Compile方法上设置断点并查看compilationContent.
笔记
查看查找区分大小写.如果您的控制器路由寻找名为Index(Index.cshtml)的视图但您已命名视图文件索引(index.cshtml),则会收到异常:
InvalidOperationException: The view ‘Index’ was not found.