简体   繁体   English

使用图片发送HTML电子邮件时使用Url.Content()

[英]Using Url.Content() when sending an html email with images

I need my app to send a confirmation email to a user. 我需要我的应用向用户发送确认电子邮件。 I have used the following method to render the view as a string: 我使用以下方法将视图呈现为字符串:

    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();
        }
    }

which I got from here . 我从这里得到的。 It works great, however my images aren't being included. 效果很好,但是没有包含我的图像。 I'm using: 我正在使用:

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

which is giving me 这给了我

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

This works fine when viewing the page on the site, however the image links don't work in the email. 在查看网站上的页面时,此方法效果很好,但是图像链接在电子邮件中不起作用。

I need it to give me me: 我需要它给我:

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

I've also tried using: 我也尝试过使用:

VirtualPathUtility.ToAbsolute()

This is what I used on a site recently: 这是我最近在一个网站上使用的:

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;
}

I could then use it to generate Absolute urls by doing Core.ResolveServerUrl("~/Resource/confirmation-email/imageName.png"); 然后,我可以通过执行Core.ResolveServerUrl("~/Resource/confirmation-email/imageName.png");使用它来生成绝对URL Core.ResolveServerUrl("~/Resource/confirmation-email/imageName.png"); (assuming you wrap the static function in a class named Core) (假设您将静态函数包装在名为Core的类中)

HTH 高温超导

There isn't a way to do this. 没有办法做到这一点。 You can add the following extension method. 您可以添加以下扩展方法。

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));
    }
}

Which you can then call like so 然后可以这样打电话给

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM