System.PlatformNotSupportedException in .NET Core 2.0 - c#

I'm trying to compile an application made in .NET Core 2.0 but every time I try to login the post method throws the following error:
System.PlatformNotSupportedException: Operation is not supported on this platform.
at System.Threading.ExecutionContext.GetObjectData(SerializationInfo info, StreamingContext context)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter.WriteObject(TextWriter writer, Object value)
at Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Could you guys help me to fix this error? I found out that multiple modifications were made in .NET Core 2.0 and maybe it doesn't support this method anymore, but it worked before.
Is there anything that can be done to get it working again?
UPDATE
I added the code where the error is thrown, it happens when the Ok object is returned.
public async Task<IActionResult> Login([FromBody]AuthRequest itemRequest)
{
try
{
var result = await _manager.ValidateUserAsync(itemRequest.Email, itemRequest.Password);
if (result.Succeeded)
{
var user = await _manager.GetUserAsync(itemRequest.Email);
return Ok(new
{
name = user.name,
administrator = user.administrator,
permissions = _manager.GetUserPermissions(user.Email)
});
}
return Unauthorized();
}
catch (Exception e)
{
return StatusCode(500);
}
}
public async Task<IEnumerable<Permission>> GetUserPermissions(string value)
{
IEnumerable<Permission> permissions;
using (var connection = GetConnection())
{
var parameters = new DynamicParameters();
parameters.Add("#email", value);
permissions = await connection.QueryAsync<Permission>("[dbo].[GetUserPermissions]", parameters, null, null, CommandType.StoredProcedure);
}
return permissions;
}
public class Permission
{
public int module { get; set; }
public bool permission { get; set; }
}

I managed to make the application work again by installing .Net Core 2.0.9!

Related

asp.net mvc framework 5.2.7 dependency injection FilterProviderCollection.GetFilters error

I have been trying to setup DI with Microsoft.Extensions.DependencyInjection for asp.net mvc framework 5.2.7 and it seems to kinda work, since i can see my own services being resolved for the controllers when i debug. Afterwards however it will throw a 'NullReferenceException' and print the following stacktrace:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.FilterProviderCollection.GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +127
System.Web.Mvc.ControllerActionInvoker.GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +37
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +193
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +494
System.Web.Mvc.<>c.<BeginExecute>b__151_1(AsyncCallback asyncCallback, Object callbackState, Controller controller) +16
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +403
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +54
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +427
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +105
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
Global.asax.cs:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
DependencyInjectionConfig.SetDependencyResolver();
}
}
Set Resolver:
public class DependencyInjectionConfig
{
public static void SetDependencyResolver()
{
var services = new ServiceCollection();
services.AddTransient<ITestService, TestService>();
AddControllersAsServices(services, typeof(DependencyInjectionConfig).Assembly.GetExportedTypes()
.Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
.Where(t => typeof(IController).IsAssignableFrom(t)
|| t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));
var serviceProvider = services.BuildServiceProvider();
var dependencyResolver = new Logic.DependencyInjection.DependencyResolver(serviceProvider);
System.Web.Mvc.DependencyResolver.SetResolver(dependencyResolver);
}
public static IServiceCollection AddControllersAsServices(IServiceCollection services, IEnumerable<Type> controllerTypes)
{
foreach (var type in controllerTypes)
{
services.AddTransient(type);
}
return services;
}
}
My DependencyResolver:
public class DependencyResolver : IDependencyResolver
{
private readonly IServiceProvider serviceProvider;
public DependencyResolver(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public object GetService(Type serviceType)
{
var service = this.serviceProvider.GetService(serviceType);
return service;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return new List<object> { GetService(serviceType) };
}
}
The problem is likely in your GetServices implementation:
public IEnumerable<object> GetServices(Type serviceType)
{
return new List<object> { GetService(serviceType) };
}
This doesn't follow the contract, because GetServices should never return a collection with elements that are null, while you are always returning a one-element collection where that element could be null.
Instead, the implementation should likely be something as follows:
public IEnumerable<object> GetServices(Type serviceType)
{
return this.serviceProvider.GetServices(serviceType);
}

Blazor | Dependency Injection error: Cannot resolve scoped service

I am new to blazor, and ef core.
I need a parameter passed into a function on my DbContext, I have created a service that has an 'int' field, but I am struggling to inject this into the context... I'm not sure what I need to do here, everything I've tried still results in an error. Some help would be great...
I'm trying to inject the "_cookieRepo" into the code, but I cannot pass an additional parameter into the constructor, when i do i get the "Cannot resolve scoped services" error.
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddDbContextFactory<OlqtContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
.LogTo(log => Debug.WriteLine(log),
new[] { DbLoggerCategory.Database.Command.Name },
Microsoft.Extensions.Logging.LogLevel.Information)
.EnableSensitiveDataLogging());
services.AddScoped<ICookieRepository, CookieRepository.CookieRepository>();
}
DbContext:
public partial class OlqtContext : DbContext
{
private readonly ICookieRepository _cookieRepository;
public OlqtContext(DbContextOptions<OlqtContext> options, ICookieRepository cookieRepository)
: base(options)
{
ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
_cookieRepository = cookieRepository;
}
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
var loginId = _cookieRepository.LoginId;
var dateTimeNow = DateTime.Now;
ChangeTracker.DetectChanges();
var modified = ChangeTracker.Entries().Where(x => x.State == EntityState.Added || x.State == EntityState.Modified || x.State == EntityState.Deleted);
foreach (var item in modified)
{
if (item.Entity is IAuditable entity)
{
if (item.State == EntityState.Added)
{
item.CurrentValues[nameof(IAuditable.CreatedByUserId)] = loginId;
item.CurrentValues[nameof(IAuditable.CreatedDate)] = dateTimeNow;
}
item.CurrentValues[nameof(IAuditable.LastModifiedByUserId)] = loginId;
item.CurrentValues[nameof(IAuditable.LastModifiedDate)] = dateTimeNow;
}
}
return base.SaveChangesAsync(cancellationToken);
}
Interface/Repo:
*Interface**
using System;
using System.Collections.Generic;
using System.Text;
namespace Olqt.CookieRepository
{
public interface ICookieRepository
{
public int LoginId { get; set; }
}
}
**Repo:**
using System;
using System.Collections.Generic;
using System.Text;
namespace Olqt.CookieRepository
{
public class CookieRepository : ICookieRepository
{
public int LoginId { get; set; }
}
}
The login ID is set here, in the loginrepo I created.
public partial class LoginRepository : GenericRepository<Login, LoginDto>, ILoginRepository
{
private readonly ICookieRepository _cookieRepository;
public LoginRepository(IDbContextFactory<OlqtContext> dbFactory, IMapper mapper, ICookieRepository cookieRepository) : base(dbFactory, mapper, cookieRepository)
{
_cookieRepository = cookieRepository;
}
public async Task<LoginDto> VerifyLoginAsync(string username, string password)
{
using var _context = GetOlqtContext();
LoginDto retval = null;
var login = await _context.Logins.Where(x => x.UserName == username && x.Password == password).FirstOrDefaultAsync();
if (login != null)
{
var ReturnLogin = new LoginDto
{
UserName = login.UserName,
Password = login.Password,
CreatedByUserId = login.LoginId
};
retval = ReturnLogin;
_cookieRepository.LoginId = login.LoginId;
}
return retval;
}
}
This is the error i receive:
An unhandled exception occurred while processing the request.
InvalidOperationException: Cannot resolve scoped service 'Olqt.CookieRepository.ICookieRepository' from root provider.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
InvalidOperationException: Cannot resolve scoped service 'Olqt.CookieRepository.ICookieRepository' from root provider.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method63(Closure , IServiceProvider , object[] )
Microsoft.EntityFrameworkCore.Internal.DbContextFactorySource<TContext>+<>c__DisplayClass4_0.<CreateActivator>b__1(IServiceProvider p, DbContextOptions<TContext> _)
Microsoft.EntityFrameworkCore.Internal.DbContextFactory<TContext>.CreateDbContext()
Olqt.Repository.Services.GenericRepository<T, T1>.GetOlqtContext() in GenericRepository.cs
return _dbFactory.CreateDbContext();
Olqt.Repository.Services.GenericRepository<T, T1>.GetAllAsync() in GenericRepository.cs
using var _context = GetOlqtContext();
Olqt.Server.Pages.Quote.Quote.OnInitializedAsync() in Quote.cs
Quotes = (await QuoteRepository.GetAllAsync())
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToPendingTasks(Task task)
Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(ref DiffContext diffContext, int newFrameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(ref DiffContext diffContext, int newFrameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(ref DiffContext diffContext, int newFrameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(ref DiffContext diffContext, int oldStartIndex, int oldEndIndexExcl, int newStartIndex, int newEndIndexExcl)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, int componentId, ArrayRange<RenderTreeFrame> oldTree, ArrayRange<RenderTreeFrame> newTree)
Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderInExistingBatch(RenderQueueEntry renderQueueEntry)
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessPendingRender()
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToRenderQueue(int componentId, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.ComponentBase.StateHasChanged()
Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync()
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.AddToPendingTasks(Task task)
Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters)
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(int componentId, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(Type componentType, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext+<>c__11<TResult>+<<InvokeAsync>b__11_0>d.MoveNext()
Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView parameters, HttpContext httpContext, Type componentType)
Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)
Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.RenderComponentAsync(ViewContext viewContext, Type componentType, RenderMode renderMode, object parameters)
Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count)
Olqt.Server.Pages.Pages__Host.<ExecuteAsync>b__35_1() in _Host.cshtml
<component type="typeof(App)" render-mode="ServerPrerendered" param-InitialState="initialTokenState" />
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
Olqt.Server.Pages.Pages__Host.ExecuteAsync() in _Host.cshtml
Layout = null;
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)

JsonConvert.DeserializeObject error mvc asp.net newtonjson

I use HttpRequestMessage my model is some different VirtualStock. My API JSON model as below
[{
"_id": "5f2d66ae6abb1d6870e926ac",
"MessageId": "EAD8B97887FFC1F180F3005056BF2302",
"MessageType": "CreateDiscount",
"RequestedBy": "AAA",
"RequestedDate": "2020-08-07T17:22:58.000Z",
"Data": {
"_id": "5f2d66ae6abb1d6870e926ad",
"Sku": "A",
"SkuId": "EAD8B97887FFC0F180F3005056BF2302",
"Price": 1759.17,
"PurchasePrice": 1768.88,
"StartDateTime": "2020-08-07T17:24:34.000Z",
"EndDateTime": "2020-09-01T00:00:00.000Z",
"VirtualStock": "1000",
"MaximumQuantityForCart": 10,
"CurrencyCode": "949"
},
"__v": 0
},
{
"_id": "5f2d65daf7168b686d9474b9",
"MessageId": "EAD8B8F92D90CDF180F3005056BF2302",
"MessageType": "UpdateDiscount",
"RequestedBy": "AAA",
"RequestedDate": "2020-08-07T17:19:26.000Z",
"Data": {
"_id": "5f2d65daf7168b686d9474c5",
"Sku": "A",
"SkuId": "EAD8B8F92D90C5F180F3005056BF2302",
"DiscountId": "8c3975a0-ea85-48e9-9c31-ea488bdad5c4",
"Price": 296.2,
"PurchasePrice": 239.91,
"StartDateTime": "2020-08-01T14:35:00.000Z",
"EndDateTime": "2020-08-07T17:23:08.000Z",
"VirtualStock": {
"Value": "100",
"IsAssigned": true
},
"MaximumQuantityForCart": 25,
"CurrencyCode": "949"
},
"__v": 0
}
]
I defined my model VirtualStock like object and nullable.
public object? VirtualStock { get; set; }
but I get error parsing how can fix this?
I saw with debug Deserialize Success but showing JSON GetDiscount method I have exceptions
controller code as below
public IActionResult Discount()
{
return View();
}
public async Task<IActionResult> GetDiscount()
{
return Json(new { data = await _log.GetAllAsync("http://0.0.0.0/DiscountLog?pagesize=9&page=16") });
}
my Repository
public async Task<IEnumerable<T>> GetAllAsync(string url)
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
var client = _clientFactory.CreateClient();
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var jsonString = await response.Content.ReadAsStringAsync();
var jsonSerializerSettings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
return JsonConvert.DeserializeObject<IEnumerable<T>>(jsonString,jsonSerializerSettings);
}
return null;
}
My error:
An unhandled exception occurred while processing the request.
NotSupportedException: The collection type 'System.Object' on
'RetailLogWeb.Models.LogItem.VirtualStock' is not supported.
System.Text.Json.JsonPropertyInfoNotNullable<TClass,
TDeclaredProperty, TRuntimeProperty,
TConverter>.GetDictionaryKeyAndValueFromGenericDictionary(ref
WriteStackFrame writeStackFrame, out string key, out object value)
NotSupportedException: The collection type 'System.Object' on
'RetailLogWeb.Models.LogItem.VirtualStock' is not supported.
System.Text.Json.JsonPropertyInfoNotNullable<TClass,
TDeclaredProperty, TRuntimeProperty,
TConverter>.GetDictionaryKeyAndValueFromGenericDictionary(ref
WriteStackFrame writeStackFrame, out string key, out object value)
System.Text.Json.JsonPropertyInfo.GetDictionaryKeyAndValue(ref
WriteStackFrame writeStackFrame, out string key, out object value)
System.Text.Json.JsonSerializer.HandleDictionary(JsonClassInfo
elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter
writer, ref WriteStack state)
System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, int
originalWriterDepth, int flushThreshold, JsonSerializerOptions
options, ref WriteStack state)
System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, object
value, Type inputType, JsonSerializerOptions options,
CancellationToken cancellationToken)
Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext
context, JsonResult result)
Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext
context, JsonResult result)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0<TFilter,
TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next,
Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed
context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter,
TFilterAsync>(ref State next, ref Scope scope, ref object state, ref
bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, object state, bool
isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed
context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State
next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, object state, bool
isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker
invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint
endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext
context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext
context)
OP figured it out as shared in the comments, but I'll provide an answer here just to close out the question. As explained in this answer, the solution was to add a variant of this line:
services.AddControllers().AddNewtonsoftJson();
This was needed because Newtonsoft.Json was removed during a recent upgrade to .NET Core, and this adds it back in. Note that this assumes you have the Microsoft.AspNetCore.Mvc.NewtonsoftJson package installed.
More info here.

I don't seem to be able to read out object from expression after passing it through component as a parameter

Blazor - .NET Core 3 Preview 6
I'm trying to build component that takes a property as lambda-expression in and then present info about that property for the user.
I seem to be able to get all the data if I declare the object and bind it as an expression on the component directly. But if I first pass the object as a parameter to a component and then, as nested, bind the expression i get an error
TestComponent:
#using System.Linq.Expressions;
#using System.Reflection;
#code
{
[Parameter]
Expression<Func<string>> For { get; set; }
protected override void OnInit()
{
var propertyInfo = ((MemberExpression)For.Body).Member as PropertyInfo;
var me = (MemberExpression)((MemberExpression)For.Body).Expression;
var ce = (ConstantExpression)me.Expression;
var fieldInfo = ce.Value.GetType().GetField(me.Member.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var thisObject = fieldInfo.GetValue(ce.Value);
}
}
WrapperComponent
#using Models
<TestComponent For="#(() => Obj.Name)"></TestComponent>
#code
{
[Parameter]
TestModel Obj { get; set; }
}
TestPage
#page "/test"
<TestComponent For="#(() => obj.Name)"></TestComponent>
<WrapperComponent Obj="#obj"></WrapperComponent>
#code
{
TestModel obj = new TestModel();
}
Running only the first component, TestComponent, works fine.
If I run the second component instead, WrapperComponent, I get the following:
NullReferenceException: Object reference not set to an instance of an object.
CustomerportalCore.Components.TestComponent.OnInit() in TestComponent.razor
var thisObject = fieldInfo.GetValue(ce.Value);
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.Server.Circuits.CircuitPrerenderer.CircuitHost_UnhandledException(object sender, UnhandledExceptionEventArgs e)
Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost.Renderer_UnhandledException(object sender, Exception e)
Microsoft.AspNetCore.Components.Browser.Rendering.RemoteRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.Rendering.Renderer.AddToPendingTasks(Task task)
Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterCollection parameters)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(ref DiffContext diffContext, int frameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(ref DiffContext diffContext, int newFrameIndex)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(ref DiffContext diffContext, int oldStartIndex, int oldEndIndexExcl, int newStartIndex, int newEndIndexExcl)
Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer renderer, RenderBatchBuilder batchBuilder, int componentId, ArrayRange<RenderTreeFrame> oldTree, ArrayRange<RenderTreeFrame> newTree)
Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.Rendering.Renderer.RenderInExistingBatch(RenderQueueEntry renderQueueEntry)
Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.Server.Circuits.CircuitPrerenderer.CircuitHost_UnhandledException(object sender, UnhandledExceptionEventArgs e)
Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost.Renderer_UnhandledException(object sender, Exception e)
Microsoft.AspNetCore.Components.Browser.Rendering.RemoteRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.Rendering.Renderer.ProcessRenderQueue()
Microsoft.AspNetCore.Components.Rendering.Renderer.AddToRenderQueue(int componentId, RenderFragment renderFragment)
Microsoft.AspNetCore.Components.RenderHandle.Render(RenderFragment renderFragment)
Microsoft.AspNetCore.Components.ComponentBase.StateHasChanged()
Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync()
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.Server.Circuits.CircuitPrerenderer.CircuitHost_UnhandledException(object sender, UnhandledExceptionEventArgs e)
Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost.Renderer_UnhandledException(object sender, Exception e)
Microsoft.AspNetCore.Components.Browser.Rendering.RemoteRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.Rendering.Renderer.AddToPendingTasks(Task task)
Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterCollection parameters)
Microsoft.AspNetCore.Components.Rendering.Renderer.RenderRootComponentAsync(int componentId, ParameterCollection initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(Type componentType, ParameterCollection initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterCollection initialParameters)
Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost+<>c__DisplayClass41_0+<<PrerenderComponentAsync>b__0>d.MoveNext()
Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext+<>c__11<TResult>+<<InvokeAsync>b__11_0>d.MoveNext()
Microsoft.AspNetCore.Components.Server.Circuits.CircuitPrerenderer.PrerenderComponentAsync(ComponentPrerenderingContext prerenderingContext)
Microsoft.AspNetCore.Mvc.Rendering.HtmlHelperComponentPrerenderingExtensions.RenderComponentAsync<TComponent>(IHtmlHelper htmlHelper, object parameters)
CustomerportalCore.Pages.Pages__Host.<ExecuteAsync>b__22_1() in _Host.cshtml
#(await Html.RenderComponentAsync<App>())</App>
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
CustomerportalCore.Pages.Pages__Host.ExecuteAsync()
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
What am I missing?
I'm no expert with Blazor, but if you invoke the expression in OnInit instead of reflecting, it seems to give me a sensible answer:
For.Compile().Invoke()
gives me "testing, testing", which is what I gave my model as a Name. This might be horrible advice, or have some unknown horrors built in though ¯(ツ)/¯
A quick search shows that there might be some memory issues by creating and evaluating a lot of Expression/Funcs, so that might be something to consider

Editing (PUT) a record in MVC5/WebAPI2 results in error "Unable to serialize the session state."

I have an MVC5 front end and a WebAPI version 2 back end. When I go to edit a record on my front end, I make my form field changes and click "Save", I immediately get the error:
This error ONLY happens when I edit a record. It works fine when creating a brand new record.
Here's my stack trace:
[SerializationException: Type 'AppTools.HelperClasses.LoggerHelper' in Assembly 'AppTools, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +10494323
System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +230
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +121
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +178
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +51
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +540
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +131
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1666
[HttpException (0x80004005): Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.]
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1754
System.Web.SessionState.SessionStateItemCollection.WriteValueToStreamWithAssert(Object value, BinaryWriter writer) +34
System.Web.SessionState.SessionStateItemCollection.Serialize(BinaryWriter writer) +628
System.Web.SessionState.SessionStateUtility.Serialize(SessionStateStoreData item, Stream stream) +240
System.Web.SessionState.SessionStateUtility.SerializeStoreData(SessionStateStoreData item, Int32 initialStreamSize, Byte[]& buf, Int32& length, Boolean compressionEnabled) +62
System.Web.SessionState.OutOfProcSessionStateStore.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) +111
System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +798
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
Here's my WebAPI PUT method:
[HttpPut]
public HttpResponseMessage Put(int id, BulletinBoard bulletinBoard)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
db.Entry(bulletinBoard).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
Here's my front end (MVC5) Edit Action method:
[HttpPost]
public ActionResult Edit(int id, BulletinBoard bulletinBoard)
{
bulletinBoard.ModifiedDate = DateTime.Now;
bulletinBoard.ModifiedBy = HttpContext.User.Identity.Name;
response = client.PutAsJsonAsync(string.Format("api/bulletinboard/put/{0}", id), bulletinBoard).Result;
//var test = response.Content.ReadAsStringAsync();
//HttpContext.Response.Write(test);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
"Cannot create a new message due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
return View("Problem");
}
}
Please help me understand why I'm getting this error!
probably issue is that you model is trying to update without id since since you have signature
public HttpResponseMessage Put(int id, BulletinBoard bulletinBoard)
So thats mean that bulletinBoard could have no setted id then you have
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
then probably your model is invalid and response should return status Status Code:400 Bad Request, but since you have some where log exception which is not serializable then it throw exeption
to solve it try
public HttpResponseMessage Put(int id, BulletinBoard bulletinBoard) {
bulletinBoard.Id = id;

Categories

Resources