在Razor视图上处理嵌入式资源的正确方法是什么? [英] What is the right way to handle Embedded Resources on a Razor View?
问题描述
我正在将一些代码从ASPX视图引擎迁移到Razor,但遇到了障碍.
I'm migrating some code from the ASPX view engine to Razor and I've run up onto a roadblock.
我有此代码:
<link rel="Stylesheet" type="text/css" href="
<%=Page.ClientScript.GetWebResourceUrl
(typeof(DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector),
"DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector.css")%>" />
这里的问题是使用Razor时,我没有Page属性.
The problem here is that with Razor, I have no Page property.
所以我退后了一步,我在想这个问题:在Razor中获取嵌入式资源的正确方法是什么?
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?
推荐答案
不幸的是,Web资源与Webforms基础结构紧密相关,如果没有Webforms基础结构,则很难重用它们.有点hacky,但是您可以编写一个助手:
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);
}
}
并在您的剃刀视图中:
<link rel="stylesheet" type="text/css" href="@Url.WebResource(typeof(DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector), "DotNetOpenAuth.OpenId.RelyingParty.OpenIdSelector.css")" />
另一种可能性是编写一个自定义HTTP处理程序/控制器,该处理程序/控制器将从程序集中读取嵌入式资源,并通过设置适当的内容类型将其流化为响应.
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.
这篇关于在Razor视图上处理嵌入式资源的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!