Get absolute path of file on content

前端 未结 5 546
轮回少年
轮回少年 2020-12-15 03:58

Is there any easy (built in) way in an asp.net mvc view to get the absolute path of a file in the content folder?

At the moment I\'m using

@Url.Cont         


        
相关标签:
5条回答
  • 2020-12-15 04:24

    This works for me:

    A helper:

    using System;
    using System.Web;
    using System.Web.Mvc;
    
    public static class UrlExtensions
    {
        public static string Content(this UrlHelper urlHelper, string contentPath, bool toAbsolute = false)
        {
            var path = urlHelper.Content(contentPath);
            var url = new Uri(HttpContext.Current.Request.Url, path);
    
            return toAbsolute ? url.AbsoluteUri : path;
        }
    }
    

    Usage in cshtml:

    @Url.Content("~/Scripts/flot/jquery.flot.menuBar.js", true)
    
    // example output:
    // http://example.com/directory/Scripts/flot/jquery.flot.menuBar.js
    
    0 讨论(0)
  • 2020-12-15 04:44
    HttpContext.Current.Server.MapPath("~/Content/images/logo.png");
    
    0 讨论(0)
  • 2020-12-15 04:47

    This will generate an absolute url to an image (or file)

    Request.Url.Scheme + "://" + Request.Url.Authority + Url.Content("~/Content/images/logo.png")
    

    This works in Asp.net Core

    Context.Request.Scheme + "://" + Context.Request.Host + Url.Content("~/images/logo.png")
    
    0 讨论(0)
  • 2020-12-15 04:48

    Url.Content does return the absolute path. What you want is the domain (and port). You can get the current domain by using:

    Request.Url.Authority
    

    Then combine this string with the absolute path string of your image. It will return the domain name and if you are on a different port will also include the port number.

    0 讨论(0)
  • 2020-12-15 04:49
    new Uri(Request.Url, Url.Content("~/Content/images/logo.png"))
    

    this calls the .ToString() of Uri. You can also put Uri in a variable and call .AbsoluteUri.

    0 讨论(0)
提交回复
热议问题