2

WebClient我有一个 data: URI,我需要使用普通的 .Net / “下载”(读取:作为流或字节数组加载)WebRequest。我怎样才能做到这一点?

我需要这个,因为我想显示一个从 SVG 生成的 XAML 文件,其中包括一些使用 data: URI 的图像。我不想总是解析 XAML,将图像保存到磁盘,然后将 XAML 更改为指向文件。我相信 WPFWebRequest在内部使用来获取这些图像。

4

1 回答 1

6

你可以用它WebRequest.RegisterPrefix()来做到这一点。您将需要实现IWebRequestCreate返回一个 customWebRequest并返回一个 custom WebResponse,它最终可用于从 URI 获取数据。它可能看起来像这样:

public class DataWebRequestFactory : IWebRequestCreate
{
    class DataWebRequest : WebRequest
    {
        private readonly Uri m_uri;

        public DataWebRequest(Uri uri)
        {
            m_uri = uri;
        }

        public override WebResponse GetResponse()
        {
            return new DataWebResponse(m_uri);
        }
    }

    class DataWebResponse : WebResponse
    {
        private readonly string m_contentType;
        private readonly byte[] m_data;

        public DataWebResponse(Uri uri)
        {
            string uriString = uri.AbsoluteUri;

            int commaIndex = uriString.IndexOf(',');
            var headers = uriString.Substring(0, commaIndex).Split(';');
            m_contentType = headers[0];
            string dataString = uriString.Substring(commaIndex + 1);
            m_data = Convert.FromBase64String(dataString);
        }

        public override string ContentType
        {
            get { return m_contentType; }
            set
            {
                throw new NotSupportedException();
            }
        }

        public override long ContentLength
        {
            get { return m_data.Length; }
            set
            {
                throw new NotSupportedException();
            }
        }

        public override Stream GetResponseStream()
        {
            return new MemoryStream(m_data);
        }
    }

    public WebRequest Create(Uri uri)
    {
        return new DataWebRequest(uri);
    }
}

这仅支持 base64 编码,但可以轻松添加对 URI 编码的支持。

然后你像这样注册它:

WebRequest.RegisterPrefix("data", new DataWebRequestFactory());

是的,这确实适用于检索数据:XAML 文件中的图像。

于 2013-02-08T18:59:34.777 回答