我刚将.NET Core 2.0迁移到.NET Core 2.1。一切都进行得很顺利,但是现在当我尝试登录时,出现以下错误:
- $exception {System.ObjectDisposedException: Cannot access a disposed object. Object name: 'IServiceProvider'。
此错误发生在以下代码段中:
public class AppContractResolver : DefaultContractResolver
{
private readonly IServiceProvider _services;
public AppContractResolver(IServiceProvider services)
{
_services = services;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var httpContextAccessor = _services.GetService<IHttpContextAccessor>();
var user = httpContextAccessor.HttpContext.User;
List<JsonProperty> properies = base.CreateProperties(type, memberSerialization).ToList();
properies = FilterOneClaimGranted(type, properies, user);
return properies;
}
问题出现在这一行:
var httpContextAccessor = _services.GetService<IHttpContextAccessor>();
这段代码在.NET Core 2.0上运行正常。
我已经尝试在启动时添加HttpContextAccessor
,但没有成功。
那么,该如何解决呢?
如果需要更多代码,请告知。我很乐意提供,但我不知道您需要哪些代码,因此我没有添加很多代码。
编辑
我已经在启动时添加了services.AddHttpContextAccessor();
,但似乎没有起作用。仍然出现错误。
编辑2:
完整的堆栈跟踪:
- $exception {System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at WebAPI.Extensions.AppContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization) in C:\Users\luukw\Desktop\stage\blacky-api\Blacky\Extensions\Resolver\AppContractResolver.cs:line 25
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.GetContractSafe(Type type)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)} System.ObjectDisposedException
services.AddHttpContextAccessor();
进行注册? - GibbonIServiceProvider
传递给你的类,而是传递实际需要使用的东西。这解决了一些边缘情况(比如你的情况),并且使得更容易看出你的类实际上使用了哪些依赖项。 - Scott Chamberlain