[英]How can I use Windows Authentication with Microsoft.Rest.ServiceClient
[英]Using singleton HttpClient with Microsoft.Rest.ServiceClient - getting System.MissingMethodException
我正在尝试重新设计我的 Azure API 客户端以将单例HttpClient
用于ServiceClient<T>
,因为多个来源建议这样做(为了性能,它也是HttpClient
建议方法,它在幕后用于Microsoft.Rest.ServiceClient
“一般来说”)
我正在使用 Microsoft.Rest.ClientRuntime.2.3.12 版本
我看到 Microsoft.Rest.ServiceClient 具有用于重用HttpClient
构造函数
protected ServiceClient(HttpClient httpClient, bool disposeHttpClient = true);
这是我的 API 客户端的构造函数,以便重用HttpClient,但是当它被调用时,它会因System.MissingMethodException
失败: Void Microsoft.Rest.ServiceClient`1..ctor(System.Net.Http.HttpClient, Boolean)
public MyAPIclient(ServiceClientCredentials credentials, HttpClient client)
: base(client, disposeHttpClient: false)
{
this._baseUri = new Uri("https://...");
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
Credentials?.InitializeServiceClient(this);
}
这就是我调用 API 客户端的方式
using (var apiClient = new MyAPIclient(credentials, HttpClientSingleton.Client))
//I get Method not found 'Void Microsoft.Rest.ServiceClient`1..ctor(System.Net.Http.HttpClient, Boolean)'
{
//some api call
}
这就是我实例化我的 http 客户端单例的方式
public static class HttpClientSingleton
{
public static readonly HttpClient Client = new HttpClient() { Timeout = TimeSpan.FromMinutes(30) };
}
为什么会出现此异常(我可以看到ServiceClient
具有ctor(httpClient, bool)
)?
如何解决这个问题?
就像 Nkosi 说的,你应该尝试恢复 nuget 包,清除你的 obj/bin 并重建。 这通常发生在事情失步时。 随着所有的影子缓存等,事情最终可能会不匹配。 我根据您的代码创建了一个小示例,并且没有任何问题。 如果您发现仍然不起作用,您应该在文件中包含更多信息,例如类声明和 using 语句,以及您使用的 .net 版本。
以下适用于 4.5.2 ServiceClient 2.3.12
using Microsoft.Rest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
using (var apiClient = new MyAPIclient(null, HttpClientSingleton.Client))
//I get Method not found 'Void Microsoft.Rest.ServiceClient`1..ctor(System.Net.Http.HttpClient, Boolean)'
{
var httpClient = apiClient.HttpClient;
}
}
public class MyAPIclient : ServiceClient<MyAPIclient>
{
protected Uri _baseUri { get; set; }
protected ServiceClientCredentials Credentials { get; set; }
public MyAPIclient(ServiceClientCredentials credentials, HttpClient client) : base(client, disposeHttpClient: false)
{
this._baseUri = new Uri("https://stackoverflow.com");
this.Credentials = credentials;
if(credentials != null)
Credentials?.InitializeServiceClient(this);
}
}
public static class HttpClientSingleton
{
public static readonly HttpClient Client = new HttpClient() { Timeout = TimeSpan.FromMinutes(30) };
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.