在 .NET Core / UWP 中为单个 HTTP 请求设置自定义 WebProxy

Set a custom WebProxy for a single HTTP request in .NET Core / UWP

我需要一个简单的 HTTP GET 请求来使用自定义代理。我在这里不是在谈论获取 Windows 默认代理设置,而是自定义代理设置。

在 Xamarin Android 应用程序中,以下代码确实有效:

string myProxy = "100.100.100.100:7777";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://my_uri"));
request.Proxy = new WebProxy(myProxy, false);`

在 Windows 通用应用程序项目中,class WebProxy 未实现。所以我按照这个答案创建了一个自定义实现:Location of IWebProxy implementation for .NET Core

我现在的代码是:

public class MyProxy : IWebProxy
{
    public Uri GetProxy(Uri destination)
    {                
       return new Uri("http://100.100.100.100:7777");
    }

    public bool IsBypassed(Uri host)
    {
        return false;
    }

    public ICredentials Credentials { get; set; }
}

然后...

request.Proxy = new MyProxy();

不过没用。事实上,如果我在 GetProxy 内部设置断点,它甚至不会被命中。 它只是忽略代理设置并使用 Windows 10 个默认设置。

虽然我们可以使用HttpWebRequest Class in UWP apps, but if we look at the Version Information of HttpWebRequest.Proxy Property, we will find this property is also not available in UWP like WebProxy Class。所以你的代码将不起作用。

在 .NET Core/UWP 中,System.Net.HttpWebRequest class 在 System.Net.Requests图书馆。

The API surface for .NET Core 5 is the same as that available for Windows 8.1 apps and is very limited compared to the surface in the .NET Framework. This is intentional and we highly encourage switching to the HttpClient API instead – that is where our energy and innovation will be focused going forward.

This library is provided purely for backward compatibility and to unblock usage of .NET libraries that use these older APIs. For .NET Core, the implementation of HttpWebRequest is actually based on HttpClient (reversing the dependency order from .NET Framework). As mentioned above, the reason for this is to avoid usage of the managed .NET HTTP stack in a UWP app context and move towards HttpClient as a single HTTP client role API for .NET developers.

更多信息,请参阅.NET Networking APIs for UWP Apps

对于 HttpClient:

For both APIs, proxy settings are automatically obtained from Internet Explorer/Microsoft Edge settings and are used for all the HTTP calls by default. This enables apps to automatically work even if the user is connected to the internet through a proxy. Neither API provides a way to specify a custom proxy for your app. However, you can choose to not use the default proxy by setting HttpClientHandler.UseProxy to false (for System.Net.Http) or HttpBaseProtocolFilter.UseProxy to false (for Windows.Web.Http).

更多信息,请参阅Demystifying HttpClient APIs in the Universal Windows Platform

所以我们现在不能对单个 HTTP 请求使用自定义代理。但欢迎您在 UserVoice 上投票以请求此功能。