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

 ̄綄美尐妖づ 提交于 2019-12-10 06:49:16

问题


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).


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7266028/asp-net-mvc-absolute-url-to-content-to-be-determines-from-outside-controller-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!