ASP.NET MVC - absolute URL to content to be determ

2019-05-04 00:13发布

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

/Areas/MyUsefulApplication/Content/_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).

2条回答
混吃等死
2楼-- · 2019-05-04 00:34

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.

查看更多
萌系小妹纸
3楼-- · 2019-05-04 00:47

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.

查看更多
登录 后发表回答