解决.net core3.1 System.InvalidCastException: Unable to cast object of type 'GrantTypeValidatingHashSet' to type 'System.Collections.IList'.

解决.net core3.1 System.InvalidCastException: Unable to cast object of type 'GrantTypeValidatingHashSet' to type 'System.Collections.IList'.

249发表于2020-08-01

今天写一个添加IdentityServer4的Client的Restful接口,使用postman测试,提交以下内容报错:

{
    "ClientId":"client22",
    "ClientName":"客户端22",
    "Description":"客户端描述22",
    "ClientUri":"http://localhost:4003",
    "LogoUri":"http://localhost:4003/logo.png",
    "AllowedGrantTypes":["client_credentials"],
    "ClientSecrets":[{"Value":"client","Description":""}],
    "AllowedScopes":["api11"],
    "RedirectUris":["http://localhost:4003"],
    "PostLogoutRedirectUris":["http://localhost:4003/signout-callback-oidc"],
    "AllowOfflineAccess":true,
    "RequireConsent":true,
    "RequirePkce":true
    
}

报错如下:

System.InvalidCastException: Unable to cast object of type 'GrantTypeValidatingHashSet' to type 'System.Collections.IList'.
   at System.Text.Json.ReadStack.AppendStackFrame(StringBuilder sb, ReadStackFrame& frame)
   at System.Text.Json.ReadStack.jsonpath()
   at System.Text.Json.ThrowHelper.AddExceptionInformation(ReadStack& readStack, Utf8JsonReader& reader, JsonException ex)
   at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
   at System.Text.Json.JsonSerializer.ReadCore(JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& readStack)
   at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
   at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext)
   at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events, IBackChannelLogoutService backChannelLogoutService)
   at IdentityServer4.Hosting.MutualTlsEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip, deflate, br
Host: localhost:5000
User-Agent: PostmanRuntime/7.24.1
Content-Length: 471
Postman-Token: fff5e41e-e3ba-4a8c-a1d0-924c17f10bdb


解决办法:

ConfigureServices中加入下面代码:

//解决方法json序列化问题:System.InvalidCastException: Unable to cast object of type 'GrantTypeValidatingHashSet' to type 'System.Collections.IList'.
services
.AddControllersWithViews(option => option.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddNewtonsoftJson();


小编蓝狐