开发者

ASP.NET MVC - absolute URL to content to be determines from outside controller or view

I have some content which is sitting in a path something like this:

/Areas/MyUsefulApplication/Conte开发者_运维问答nt/_awesome_template_bro/Images/MyImage.png

Is there a way get a fully qualified absolute URL to that path without being in a controller or view (where url helpers are readily available).


You could write an extension method:

public static class UrlExtensions
{
    public static Uri GetBaseUrl(this UrlHelper url)
    {
        var uri = new Uri(
            url.RequestContext.HttpContext.Request.Url,
            url.RequestContext.HttpContext.Request.RawUrl
        );
        var builder = new UriBuilder(uri) 
        { 
            Path = url.RequestContext.HttpContext.Request.ApplicationPath, 
            Query = null, 
            Fragment = null 
        };
        return builder.Uri;
    }

    public static string ContentAbsolute(this UrlHelper url, string contentPath)
    {
        return new Uri(GetBaseUrl(url), url.Content(contentPath)).AbsoluteUri;
    }
}

and then assuming you have an instance of UrlHelper:

string absoluteUrl = urlHelper.ContentAbsolute("~/Areas/MyUsefulApplication/Content/_awesome_template_bro/Images/MyImage.png");

If you need to do this in some other part of the code where you don't have access to an HttpContext and build an UrlHelper, well, you shouldn't as only parts of your code that have access to it should deal with urls. Other parts of your code shouldn't even know whan an url means.


The main question is of course: Where would you like to get the URL then if not in a controller or view? What other places are there in an Asp.net MVC application?

If you're taking about other app tiers that aren't aware of the web UI front-end then that would be a bit tricky. These apps (assemblies) could have custom configuration where you could put web app path root and they could use that. but you'd have to change it for production.

Or add a System.Web reference to your other app and access current HttpContext as Darin showed you which is an even nicer solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜