asp.net mvc image path and virtual directory

后端 未结 4 1732
死守一世寂寞
死守一世寂寞 2021-02-11 02:59

I know this has to be a duplicate, but I\'ve been wading through the hordes of information on this and I can\'t get it work.

I\'m trying to get a site working on a clien

4条回答
  •  终归单人心
    2021-02-11 03:45

    This code

    public static class Helpers
    {
      public static Uri FullyQualifiedUri( this HtmlHelper html , string relativeOrAbsolutePath )
      {
        Uri        baseUri  = HttpContext.Current.Request.Url ;
        string     path     = UrlHelper.GenerateContentUrl( relativeOrAbsolutePath, new HttpContextWrapper( HttpContext.Current ) ) ;
        Uri        instance = null ;
        bool       ok       = Uri.TryCreate( baseUri , path , out instance ) ;
        return instance ; // instance will be null if the uri could not be created
      }
    }
    

    should work for pretty much any URI you can throw at it.

    One thing to note, though: page-relative URIs (such as foo/bar/image.png) might not resolve the way you think they might, especially if the URI references a directory, so you get the default page (i.e., http://localhost/foo/bar could be an actual resource, in which case the URI is complete, or it could be incomplete, in which case Asp.Net MVC's routing fills in the blanks. All the request has is the original URI. If you want to fix that, you'll need to get the RouteData for the request and interrogate it for the details.

    Here's how things resolve with a web app rooted at http://localhost/MyApp and invoking the Html helper method in different ways from the About view of the Home controller.

    • ~
      • resolves to http://localhost/MyApp/
    • /
      • resolve to `http://localhost/
    • ~/
      • resolves to http://localhost/MyApp/
    • foo/bar/myImage.png
      • resolves to http://localhost/MyApp/Home/foo/bar/myImage.png
    • /foo/bar/myImage.png
      • resolves to http://localhost/foo/bar/myImage.png
    • ~/foo/bar/myImage.png
      • resolves to http://localhost/MyApp/foo/bar/myImage.png
    • http://somesite.com/foo/bar/myImage.png
      • resolves to http://somesite.come/foo/bar/myImage.png
    • http://somesite.com:123/foo/bar/myImage.png
      • resolves to http://somesite.come:123/foo/bar/myImage.png
    • ftp://somesite.com/foo/bar/myImage.png
      • resolves to ftp://somesite.come:123/foo/bar/myImage.png
    • mailto://local-part@domain.com
      • resolves to mailto:local-part@domain.com

提交回复
热议问题