ASP.NET MVC-要从外部控制器或视图确定的内容的绝对URL [英] ASP.NET MVC - absolute URL to content to be determines from outside controller or view

查看:69
本文介绍了ASP.NET MVC-要从外部控制器或视图确定的内容的绝对URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些内容位于这样的路径中:

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


/ Areas / MyUsefulApplication / Content / _awesome_template_bro / Images / MyImage.png

/Areas/MyUsefulApplication/Content/_awesome_template_bro/Images/MyImage.png

有没有一种方法可以获取到该路径的完全限定的绝对URL,而无需出现在控制器或视图中(其中url帮助器是随时可用)。

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

推荐答案

您可以编写扩展方法:

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;
    }
}

,然后假设您有一个UrlHelper实例:

and then assuming you have an instance of UrlHelper:

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

如果您需要在无法访问的代码的其他部分中执行此操作一个HttpContext并构建一个UrlHelper,那么,您不应该只因为可以访问它的部分代码才能处理url。您代码的其他部分甚至都不知道网址的含义。

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.

这篇关于ASP.NET MVC-要从外部控制器或视图确定的内容的绝对URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆