更改Image.Source的WebRequest

时间:2015-11-10 14:31:53

标签: c# windows-runtime uwp

我需要提供一个json作为身份验证的post请求,以便访问Windows 10应用程序中的图像。我想要覆盖从Web加载图像以注入我的json时ImageSource的默认行为。

我已设法覆盖http:,https:等的默认IWebRequestCreate处理程序。但是,如果将Image.Source设置为URL,则不会调用它,但会为每个其他请求调用它。我在这做错了什么?

这是我将IWebRequestCreate处理程序“注入”默认值的代码。

public class UserImageWebRequest : IWebRequestCreate
{

    public WebRequest Create(Uri uri)
    {

        if (!string.IsNullOrEmpty(uri.OriginalString))
        {
            if (uri.OriginalString.StartsWith("http://uxim.test.com/"))
            {
                string userId = WebUtility.UrlDecode(uri.OriginalString.Replace("http://uxim.test.com/", ""));

                return HttpWebRequest.CreateHttp("http://lorempixel.com/48/48/abstract");
            }
            else
            {
                if (uri.Scheme != null)
                {
                    var key = uri.Scheme + ":";

                    return GetDefaultCreatorForScheme(key).Create(uri);
                }
            }                
        }

        return null;
    }

    private static IWebRequestCreate GetDefaultCreatorForScheme(string scheme)
    {
        string key = "http:";

        if (!string.IsNullOrEmpty(scheme))
        {
            string nkey = "";
            if (!scheme.EndsWith(":"))
                nkey = scheme + ":";
            else
                nkey = scheme;

            if (defaultCreators.ContainsKey(nkey))
                key = nkey;
        }

        return defaultCreators[key];
    }

    private static Dictionary<string, IWebRequestCreate> defaultCreators = new Dictionary<string, IWebRequestCreate>();
    public static void Register()
    {
        // a little bit reflection here in my life, a little bit of hacking by my side, a little bit of cheating is all i need!

        Type webRequest = typeof(System.Net.WebRequest);
        IList prefixList = (IList)webRequest.GetProperty("PrefixList", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null, null);          

        IEnumerator enumerator = prefixList.GetEnumerator();
        while (enumerator != null && enumerator.MoveNext())
        {
            var itemType = enumerator.Current.GetType();
            var fields = itemType.GetFields();
            var creatorField = fields.FirstOrDefault(A => A.Name == "Creator");
            var prefxField = fields.FirstOrDefault(A => A.Name == "Prefix");

            if (creatorField != null && prefxField != null)
            {
                // remember default creators
                defaultCreators.Add(
                    prefxField.GetValue(enumerator.Current) as string, 
                    creatorField.GetValue(enumerator.Current) as IWebRequestCreate);

                // override default creators
                creatorField.SetValue(enumerator.Current, new UserImageWebRequest());
            }
        }
    }
}

0 个答案:

没有答案