Cannot debug EmbeddedResource views loaded via custom VirtualPathProvider

ぃ、小莉子 提交于 2019-12-03 11:57:56

I had the same problem and finally got it working by using a custom RazorHost. It seems that the physical file location is resolved using the HostingEnvironment.MapPath() method which does not return the correct result for embedded files.

What I did:

public class MyCustomRazorHostFactory : WebRazorHostFactory
{
    public override System.Web.WebPages.Razor.WebPageRazorHost CreateHost( string virtualPath, string physicalPath )
    {
        // Implementation stolen from MvcRazorHostFactory :)
        var host = base.CreateHost( virtualPath, physicalPath );

        if( !host.IsSpecialPage )
        {
            return new MyCustomRazorHost( virtualPath, physicalPath );
        }

        return host;
    }
}

public class MyCustomRazorHost : MvcWebPageRazorHost
{
    public MyCustomRazorHost( string virtualPath, string physicalPath )
        : base( virtualPath, physicalPath )
    {
        if( MyMagicHelper.IsEmbeddedFile( virtualPath ) )
        {
            PhysicalPath = MyMagicHelper.GetPhysicalFilePath(virtualPath);
        }
    }
}

// Simplified for demonstration purpose
public static class MyMagicHelper
{
    public static bool IsEmbeddedFile(string virtualPath)
    {
        // ... check if the path is an embedded file path
    }

    public static string GetPhysicalFilePath(string virtualPath)
    {
        // ... resolve the virtual file and return the correct physical file path
    }
}

As a last step you need to tell ASP.NET which host factory it should use. This is done in the web.config:

<system.web.webPages.razor>
    <host factoryType="My.Custom.Namespace.MyCustomRazorHostFactory" />
</system.web.webPages.razor>

I know my answer comes a bit late but hopefully someone else can make use of it when stumbling across this question as I did. :)

I tried playing with your code a bit, and when I added a test aspx in the resources, debugging appeared to work fine. I was able to set a BP in Page_Load, and it git there.

You can see my change in https://github.com/davidebbo/EmbeddedResourceVirtualPathProvider

Note that I disabled the fallback logic as I wanted to focus on the embedded case, though I don't think that makes a difference.

Note that I'm using VS2012, so I also had to upgrade the project/sln (but they'll still work in 2010).

The reason ASP.NET is generating the http line pragma is that it can't find the physical aspx file at the standard location (i.e. what MapPath would return). There is actually a little known way to always turn on this behavior: set urlLinePragmas=true in the section (http://msdn.microsoft.com/en-us/library/system.web.configuration.compilationsection.urllinepragmas.aspx).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!