结合相对基本URI使用相对路径 [英] Combine relative baseUri with relative path

查看:823
本文介绍了结合相对基本URI使用相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找一个干净的方式相对基准URI与另一个相对路径结合起来。我试过以下,但乌里(乌里,字符串) UriBuilder(URI)需要绝对URI(投掷InvalidOperationException异常:此操作不支持相对URI)

I'm looking for a clean way to combine a relative base Uri with another relative path. I've tried the following, but Uri(Uri, string) and UriBuilder(Uri) require absolute Uris (throwing InvalidOperationException: This operation is not supported for a relative URI).

// where Settings.Default.ImagesPath is "~/path/to/images"
// attempt 1
_imagePath = new Uri(Settings.Default.ImagesPath, image);

// attempt 2
UriBuilder uriBuilder = new UriBuilder(Settings.Default.ImagesPath);
uriBuilder.Path += image;
_imagePath = uriBuilder.Uri;

我不想做任何丑陋的字符串操作,以确保基本路径以斜线等结束。

I don't want to do any ugly string manipulation to make sure the base path ends with a trailing slash, etc.

推荐答案

这仍然是一个有点混乱,比我想的,但它的工作原理。

This is still a bit messier than I'd like, but it works.

public static class UriExtensions
{
    public static Uri Combine(this Uri relativeBaseUri, Uri relativeUri)
    {
        if (relativeBaseUri == null)
        {
            throw new ArgumentNullException("relativeBaseUri");
        }

        if (relativeUri == null)
        {
            throw new ArgumentNullException("relativeUri");
        }

        string baseUrl = VirtualPathUtility.AppendTrailingSlash(relativeBaseUri.ToString());
        string combinedUrl = VirtualPathUtility.Combine(baseUrl, relativeUri.ToString());

        return new Uri(combinedUrl, UriKind.Relative);
    }
}

下面是一个例子用法:

Uri imageUrl = new Uri("profile.jpg", UriKind.Relative);
Uri baseImageUrl = new Uri("~/path/to/images", UriKind.Relative);
Uri combinedImageUrl = baseImageUrl.Combine(image);

该combinedImageUrl是
    〜/路径/到/图像/ profile.jpg

The combinedImageUrl is ~/path/to/images/profile.jpg

这篇关于结合相对基本URI使用相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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