get absolute path for an image to send in email

别说谁变了你拦得住时间么 提交于 2019-12-11 08:06:05

问题


I have a view (with one or more images) that I also want to use as the body of an email message. The Model serving the view uses Url.Content() to retrieve the absolute image path. This approach works fine for web pages, but when I render the exact same view as the body of the email, then the image can not be found which is suggested by the incomplete path from the rendered html.

 <img src="/Media/fe882a1d-3b77-4264-ab91-cade985ecbed.JPG"/>

I know that this problem can be fixed if I could access the full url such as with Url.Action with the

Request.Url.Scheme

overload for protocol. Is there a way to determine the fully qualified URL from Url.Content?


回答1:


Try writting your own url extension method and resolve with the help of Uri.GetLeftPart & UriPartial.Authority

public static class UrlExtensions
{
  public static string AbsoluteContent(this UrlHelper urlHelper
                                     , string contentPath)
  {
   Uri requestUrl = urlHelper.RequestContext.HttpContext.Request.Url;

   string absolutePath = string.Format("{0}{1}",
                          requestUrl.GetLeftPart(UriPartial.Authority),
                          urlHelper.Content(contentPath));
   return absolutePath;

  }

}

Then use Url.AbsoluteContent("~/media/image.jpeg") in your pages. It will render http://domain/media/image.jpeg



来源:https://stackoverflow.com/questions/22711235/get-absolute-path-for-an-image-to-send-in-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!