1

Using Net Core 6 I have the following Page Model:

public class IndexModel : PageModel {

  public String AvatarUrl { get; set; }

  public IndexModel() { }

  public void OnGet() {

    AvatarUrl = Url.Content("~/avatar.jpg");

  }

}

How to get Absolute Content's Url instead?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • Any reason you asked this twice? https://stackoverflow.com/questions/73873667/get-content-url-in-razor-page – DavidG Sep 27 '22 at 20:51
  • @Victor The other question was different. I asked how to get the URL in the HTML code instead of doing it on IndexModel. I solved it so I deleted. The base code was similar but the question was different. – Miguel Moura Sep 27 '22 at 21:08

1 Answers1

2

Inspired by this answer, modified as follows. And it works for me.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;

namespace PageModelDemo
{
    public static class UrlExtensions
    {
        public static string Content(this IUrlHelper urlHelper, string contentPath, bool toAbsolute = false)
        {
            var path = urlHelper.Content(contentPath);
            var url = string.Format("{0}://{1}{2}", urlHelper.ActionContext.HttpContext.Request.Scheme, urlHelper.ActionContext.HttpContext.Request.Host, path);

            return toAbsolute ? url : path;
        }
    }
}

enter image description here

enter image description here

Jason Pan
  • 15,263
  • 1
  • 14
  • 29