使用Asp.Net Core时,如何查看为Razor Page生成的代码?

前端之家收集整理的这篇文章主要介绍了使用Asp.Net Core时,如何查看为Razor Page生成的代码?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用Asp.Net,很容易看到Razor View Engine生成代码添加编译错误,错误页面将提供对Razor页面源的访问.

这改变了Asp.Net Core,我在某处读到了在内存中创建代码并且不允许轻松访问该代码.

问:有人知道如何使用Asp.Net Core访问生成的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.

猜你在找的.NET Core相关文章