我需要通过代理转发由C# Graph发出的HTTP请求。
在文档中,我找不到有关代理设置的任何信息。我目前发现的唯一可行方法是更改全局代理设置:
System.Net.GlobalProxySelection.Select = proxy;
or
System.Net.WebRequest.DefaultWebProxy = proxy;
可悲的是,在我的情况下,如果不将所有与图形相关的特性移动到一个单独的进程中(因为其余的主进程需要在没有代理的情况下运行),这是不可能的。
所以我的问题是:
发布于 2018-02-13 22:19:56
您可以在实例化GraphServiceClient时设置代理。
更新6/9/2021
现在有一个更好的使用GraphClientFactory的方法。
HttpClient httpClient = GraphClientFactory.Create(GetClientCredentialProvider(), "v1.0", "Global", new WebProxy(""));
var graphServiceClient = new(httpClient);
旧答案
System.Net.Http.HttpClientHandler httpClientHandler = new System.Net.Http.HttpClientHandler()
{
AllowAutoRedirect = false,
Proxy = new WebProxy() // TODO: Set your proxy settings.
};
HttpProvider httpProvider = new HttpProvider(httpClientHandler, true);
GraphServiceClient client = new GraphServiceClient("https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = await goGetSomeTokenNow();
requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", token);
}), httpProvider);
发布于 2021-07-27 04:11:00
Microsoft.Graph 4+在这文章中有一种新的方法。但是我不得不使用两种方式来实现这一点,因为我们的蔚蓝的adfs只有来自浏览器的auth请求。希望这对其他人都有帮助。
private GraphServiceClient GetGraphClient()
{
string[] scopes = new string[] { "User.Read", "User.ReadBasic.All", "Mail.Read", "Mail.ReadWrite", "Mail.Send" };
var msalFactory = new MsalHttpClientFactoryOwn(_configuration);
IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
.Create("")
.WithTenantId("")
.WithHttpClientFactory(msalFactory)
.Build();
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);
HttpClient httpClient = GraphClientFactory.Create(authProvider, "v1.0", "Global", msalFactory.GetWebProxy());
var graphClient = new GraphServiceClient(httpClient);
return graphClient;
}
public class MsalHttpClientFactoryOwn : IMsalHttpClientFactory
{
private readonly IConfiguration configuration;
public ProxiedHttpClientFactory(IConfiguration configuration)
{
this.configuration = configuration;
}
public HttpClient GetHttpClient()
{
var proxyHttpClientHandler = new HttpClientHandler()
{
UseProxy = true,
UseDefaultCredentials = false,
Credentials = GetNetworkCredentials(),
Proxy = GetWebProxy()
};
var httpClient = new HttpClient(proxyHttpClientHandler);
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
httpClient.Timeout = TimeSpan.FromMinutes(30);
return httpClient;
}
public WebProxy GetWebProxy()
{
var proxy = new WebProxy
{
Address = new Uri("proxy address"),
BypassProxyOnLocal = false,
UseDefaultCredentials = false,
Credentials = GetNetworkCredentials()
};
return proxy;
}
private NetworkCredential GetNetworkCredentials()
{
var networkCreds = new NetworkCredential(u, p);
return networkCreds;
}
}
https://stackoverflow.com/questions/48769325
复制相似问题