您可以编写一个主题感知图像助手:
public static class HtmlExtensions
{
public static IHtmlString ThemeAwareImage(
this HtmlHelper htmlHelper,
string image,
string alt = ""
)
{
var context = htmlHelper.ViewContext.HttpContext;
var theme = context.Session["theme"] as string;
if (string.IsNullOrEmpty(theme))
{
// the theme was not found in the session
// => go and fetch it from your dabatase
string currentUser = context.User.Identity.Name;
theme = GetThemeFromSomeDataStore(currentUser);
// cache the theme in the session for subsequent calls
context.Session["theme"] = theme;
}
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var img = new TagBuilder("img");
img.Attributes["alt"] = alt;
img.Attributes["src"] = urlHelper.Content(
string.Format("~/images/{0}/{1}", theme, image)
);
return new HtmlString(img.ToString(TagRenderMode.SelfClosing));
}
}
可以在您的视图中使用它来渲染这些图像:
@Html.ThemeAwareImage("foo.jpg", "This is the foo image")
作为使用Session
存储当前用户主题的更好选择,您可以将其缓存在 cookie 中,甚至更好地将其作为您的路线的一部分,在这种情况下,您的网站将更加 SEO 友好。