Search code examples
asp.net-mvc-3razorembedded-resource

What is the right way to handle Embedded Resources on a Razor View?


I'm migrating some code from the ASPX view engine to Razor and I've run up onto a roadblock.

I have this code:

<link rel="Stylesheet" type="text/css" href="
    <%=Page.ClientScript.GetWebResourceUrl
        (typeof(DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector), 
        "DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector.css")%>" />

The problem here is that with Razor, I have no Page property.

So I took a step back for a second, and I'm looking at this wondering: What is the right way to get embedded resources in Razor?

I've spent a good bit of time trying to find solutions on this subject, but I haven't really found anything other than "wrap a new Page in a helper"

Is that the only way to do it? Or is there something more correct?


Solution

  • Unfortunately the web resources are quite tied to the webforms infrastructure and it is difficult to reuse them without it. So a bit hacky but you could write a helper:

    public static class UrlExtensions
    {
        public static string WebResource(this UrlHelper urlHelper, Type type, string resourcePath)
        {
            var page = new Page();
            return page.ClientScript.GetWebResourceUrl(type, resourcePath);
        }
    }
    

    and in your razor view:

    <link rel="stylesheet" type="text/css" href="@Url.WebResource(typeof(DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector), "DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector.css")" />
    

    Another possibility is to write a custom HTTP handler/controller which will read the embedded resource from the assembly and stream it to the response by setting the proper content type.