【问题标题】:Using Url.Content() when sending an html email with images在发送带有图像的 html 电子邮件时使用 Url.Content()
【发布时间】:2012-05-31 05:26:43
【问题描述】:

我需要我的应用向用户发送确认电子邮件。我使用以下方法将视图呈现为字符串:

    public string RenderViewToString<T>(string viewPath, T model)
    {
        using (var writer = new StringWriter())
        {
            var view = new WebFormView(viewPath);
            var vdd = new ViewDataDictionary<T>(model);
            var viewCxt = new ViewContext(ControllerContext, view, vdd, new TempDataDictionary(), writer);
            viewCxt.View.Render(viewCxt, writer);
            return writer.ToString();
        }
    }

我从here 得到的。它工作得很好,但是我的图像不包括在内。我正在使用:

<img src="<%:Url.Content("~/Resource/confirmation-email/imageName.png") %>"

这是给我的

http://resource/confirmation-email/imageName.png

在查看网站上的页面时可以正常使用,但是图像链接在电子邮件中不起作用。

我需要它给我:

http://domain.com/application/resource/confirmation-email/imageName.png

我也尝试过使用:

VirtualPathUtility.ToAbsolute()

【问题讨论】:

    标签: asp.net html email image


    【解决方案1】:

    没有办法做到这一点。您可以添加以下扩展方法。

    using System.Web.Mvc;
    
    public static class UrlHelperExtensions
    {
        public static string ToAbsoluteUrl(this UrlHelper helper, string relativeUrl) {
            if (Request.IsSecureConnection)
                return string.Format("https://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
            else
                return string.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
        }
    }
    

    然后你可以这样调用

    <img src="<%:Url.ToAbsoluteUrl("~/Resource/confirmation-email/imageName.png") %>" ...
    

    【讨论】:

    • 这与使用 Url.Content 相同...电子邮件需要绝对 URI 才能知道从何处提供图像。
    【解决方案2】:

    这是我最近在一个网站上使用的:

    public static string ResolveServerUrl(string serverUrl, bool forceHttps = false, bool getVirtualPath = true)
    {
        if (getVirtualPath)
        serverUrl = VirtualPathUtility.ToAbsolute(serverUrl);
    
        if (serverUrl.IndexOf("://") > -1)
        return serverUrl;
    
        string newUrl = serverUrl;
        Uri originalUri = System.Web.HttpContext.Current.Request.Url;
        newUrl = (forceHttps ? "https" : originalUri.Scheme) + "://" + originalUri.Authority + newUrl;
        return newUrl;
    }
    

    然后我可以通过 Core.ResolveServerUrl("~/Resource/confirmation-email/imageName.png"); 使用它来生成绝对网址(假设您将静态函数包装在名为 Core 的类中)

    HTH

    【讨论】:

      猜你喜欢
      • 2013-11-11
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 2011-08-27
      • 2017-02-23
      • 2018-09-26
      • 1970-01-01
      相关资源
      最近更新 更多