Unable to execute groupby query using OData V4 query syntax in Web API - c#

I am trying to upgrade my web api to use OData V4 query syntax. After upgrading the dlls am able to issue $filter and $select queries for my web api.
But When I issue a request like https://localhost:65000/api/Entitlement?$apply=groupby((Grade)), getting below exception (am using NHibernate ORM)
{
"message": "An error has occurred.",
"exceptionMessage": "MemberInitExpression",
"exceptionType": "System.NotSupportedException",
"stackTrace": " at NHibernate.Linq.Visitors.HqlGeneratorExpressionTreeVisitor.VisitExpression(Expression expression)\r\n at NHibernate.Linq.Visitors.ResultOperatorProcessors.ProcessGroupBy.<>c__DisplayClass1.<Process>b__0(Expression k)\r\n at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()\r\n at System.Linq.Buffer`1..ctor(IEnumerable`1 source)\r\n at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)\r\n at NHibernate.Linq.Visitors.ResultOperatorProcessors.ProcessGroupBy.Process(GroupResultOperator resultOperator, QueryModelVisitor queryModelVisitor, IntermediateHqlTree tree)\r\n at NHibernate.Linq.Visitors.ResultOperatorProcessors.ResultOperatorProcessor`1.Process(ResultOperatorBase resultOperator, QueryModelVisitor queryModel, IntermediateHqlTree tree)\r\n at NHibernate.Linq.Visitors.ResultOperatorProcessors.ResultOperatorMap.Process(ResultOperatorBase resultOperator, QueryModelVisitor queryModel, IntermediateHqlTree tree)\r\n at NHibernate.Linq.Visitors.QueryModelVisitor.VisitResultOperator(ResultOperatorBase resultOperator, QueryModel queryModel, Int32 index)\r\n at Remotion.Linq.Clauses.ResultOperatorBase.Accept(IQueryModelVisitor visitor, QueryModel queryModel, Int32 index)\r\n at Remotion.Linq.QueryModelVisitorBase.VisitResultOperators(ObservableCollection`1 resultOperators, QueryModel queryModel)\r\n at Remotion.Linq.QueryModelVisitorBase.VisitQueryModel(QueryModel queryModel)\r\n at NHibernate.Linq.Visitors.QueryModelVisitor.GenerateHqlQuery(QueryModel queryModel, VisitorParameters parameters, Boolean root)\r\n at NHibernate.Linq.NhLinqExpression.Translate(ISessionFactoryImplementor sessionFactory)\r\n at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryIdentifier, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory)\r\n at NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters)\r\n at NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow)\r\n at NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression queryExpression)\r\n at NHibernate.Linq.DefaultQueryProvider.PrepareQuery(Expression expression, IQuery& query, NhLinqExpression& nhQuery)\r\n at NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)\r\n at NHibernate.Linq.DefaultQueryProvider.Execute[TResult](Expression expression)\r\n at Remotion.Linq.QueryableBase`1.System.Collections.IEnumerable.GetEnumerator()\r\n at System.Linq.Enumerable.<OfTypeIterator>d__95`1.MoveNext()\r\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\r\n at MatrixGroup.Bmx.Server.Filters.UnitOfWorkFilterAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)\r\n at System.Web.Http.Filters.ActionFilterAttribute.OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}

Related

Ninject Serilization error when calling new StandardKernel

When I try to call
var ninjectKernel = new StandardKernel();
I get the below error. I can successfully use ninject with constructor injection. I only get this error when I try to grab a service by hand.
{"Message":"An error has occurred.","ExceptionMessage":"Type
'Ninject.Web.WebApi.NinjectDependencyResolver' in assembly
'Ninject.Web.WebApi, Version=3.3.1.0, Culture=neutral,
PublicKeyToken=c7192dc5380945e7' is not marked as
serializable.","ExceptionType":"System.Runtime.Serialization.SerializationException","StackTrace":"
at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName,
String typeName)\r\n at
Ninject.Modules.AssemblyNameRetriever.GetAssemblyNames(IEnumerable1 filenames, Predicate1 filter)\r\n at
Ninject.Modules.CompiledModuleLoaderPlugin.LoadModules(IEnumerable1 filenames)\r\n at Ninject.Modules.ModuleLoader.LoadModules(IEnumerable1 patterns)\r\n
at Ninject.KernelBase.Load(IEnumerable1 filePatterns)\r\n at Ninject.KernelBase..ctor(IComponentContainer components, INinjectSettings settings, INinjectModule[] modules)\r\n at Ninject.KernelBase..ctor(INinjectModule[] modules)\r\n at Ninject.StandardKernel..ctor(INinjectModule[] modules)\r\n at Controllers.Controllers.TagController.GetTags(TagEnum tagType) in C:\\Users\\george\\Desktop\\NewScp\\SCP\\UI\\Controllers\\TagController.cs:line 39\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary2 arguments, CancellationToken
cancellationToken)\r\n--- End of stack trace from previous location
where exception was thrown ---\r\n at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Controllers.ApiControllerActionInvoker.d__1.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Controllers.ActionFilterResult.d__5.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()"}

What is Local value serialization error in kafka?

I recently went through Confluent Kafka library in C# .net 4.7.2 framework version. But, many times I faced Local Value serialization error. Is this error is a generic one? or this error tells anything specifically? I'm not sure when will this error raises?
var rs = (RecordSchema)RecordSchema.Parse(#"{
""namespace"": ""Confluent.Kafka.Examples.AvroSpecific"",
""type"": ""record"",
""name"": ""ProduceConsumeUser2"",
""fields"": [
{""name"": ""name"", ""type"": ""string""},
{""name"": ""favorite_number"", ""type"": [""int"", ""null""]},
{""name"": ""favorite_color"", ""type"": [""string"", ""null""]}
]}");
using (var schemaRegistry = new CachedSchemaRegistryClient(schemaRegistryConfig)){
using (var genericProducer = new ProducerBuilder<string, GenericRecord>(producerConfig)
.SetValueSerializer(new AvroSerializer<GenericRecord>(schemaRegistry).AsSyncOverAsync())
.Build())
{
var genericRecord = new GenericRecord(rs);
genericRecord.Add("name", "my name 2");
genericRecord.Add("favorite_number", 44);
genericRecord.Add("favorite_color", null);
var message = new Message<string, GenericRecord>
{
Key = contentEventName,
Value = genericRecord
};
Task.Run(() => genericProducer.ProduceAsync(contentEventName, message)).ConfigureAwait(false).GetAwaiter().GetResult();
}}
Error we get:
"Error":{
"Code":-161,
"IsFatal":false,
"Reason":"Local: Value serialization error",
"IsError":true,
"IsLocalError":true,
"IsBrokerError":false
},
"Message":"Local: Value serialization error",
"Data":{ },
"InnerException":{
"ClassName":"System.Threading.Tasks.TaskCanceledException",
"Message":"A task was canceled.",
"Data":null,
"InnerException":null,
"HelpURL":null,
"StackTraceString":" at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.RestService.<ExecuteOnOneInstanceAsync>d__9.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.RestService.<RequestAsync>d__10`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.RestService.<RegisterSchemaAsync>d__18.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.CachedSchemaRegistryClient.<RegisterSchemaAsync>d__21.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.Serdes.GenericSerializerImpl.<Serialize>d__8.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Confluent.SchemaRegistry.Serdes.AvroSerializer`1.<SerializeAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)\r\n at Confluent.Kafka.Producer`2.<ProduceAsync>d__52.MoveNext()",
"RemoteStackTraceString":null,
"RemoteStackIndex":0,
"ExceptionMethod":"8\nThrowForNonSuccess\nmscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\nSystem.Runtime.CompilerServices.TaskAwaiter\nVoid ThrowForNonSuccess(System.Threading.Tasks.Task)",
"HResult":-2146233029,
"Source":"mscorlib",
"WatsonBuckets":null
},
"StackTrace":" at Confluent.Kafka.Producer`2.<ProduceAsync>d__52.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()\r\n at LogEvent(String contentEventName, IDictionary`2 e, RecordSchemaName re)",
"HelpLink":null,
"Source":"Confluent.Kafka",
"HResult":-2146233088
I cannot be for certain. But I got to this page because I had the same exception details /issue...
For me, solving the issue was making sure I had the correct credentials for the Schema Registry. DOH! Hope this helps for at least someone else!
In my C# test using the Confulent.Kafka and Confluent.SchemaRegistry the (username:password) are that exact syntax with the (:) colon in one string
string credentials ="MyUserName:mypassword";
var schemaRegistryConfig = new SchemaRegistryConfig()
{
Url = config.GetValue<string>("ConfluentCloud:SchemaRegistry:Url", string.Empty),
BasicAuthUserInfo = config.GetValue<string>("ConfluentCloud:SchemaRegistry:Credentials", string.Empty),
};
// no serializer required for string key
using (var schemaRegistry = new CachedSchemaRegistryClient(schemaRegistryConfig))
... etc. etc.

Forward ASP.Net WebAPI request to another API

I am trying to forward request from one API to another one like this:
protected Task<HttpResponseMessage> ForwardRequestToSomeApi()
{
string forwardUri = "https://some.api" + Request.RequestUri.PathAndQuery;
Request.Headers.Remove("Host");
Request.RequestUri = new Uri(forwardUri);
if (Request.Method == HttpMethod.Get)
{
Request.Content = null;
}
return new HttpClient().SendAsync(Request, HttpCompletionOption.ResponseHeadersRead);
}
but when sending PUT request I get:
Cannot close stream until all bytes are written.
Full exception info:
{"Message":"An error has occurred.","ExceptionMessage":"An error occurred while sending the request.","ExceptionType":"System.Net.Http.HttpRequestException","StackTrace":"
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__1`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"The request was aborted: The request was canceled.","ExceptionType":"System.Net.WebException","StackTrace":"
at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting)\r\n
at System.Net.ConnectStream.System.Net.ICloseEx.CloseEx(CloseExState closeState)\r\n
at System.Net.ConnectStream.Dispose(Boolean disposing)\r\n
at System.IO.Stream.Close()\r\n
at System.Net.Http.HttpClientHandler.<>c__DisplayClass109_0.<GetRequestStreamCallback>b__0(Task task)","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Cannot close stream until all bytes are written.","ExceptionType":"System.IO.IOException","StackTrace":"
at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting)"}}}
Inner exception :
IOException Message: "Cannot close stream until all bytes are
written." StackTrace: at
System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean
aborting)
Update:
Provided above code is fully working, the problem was how I attempted to use it. In my main API I had next webapi action:
[HttpPut]
public Task<HttpResponseMessage> Create(string id, Foo model)
{
return ForwardRequestToSomeApi();
}
The problem here is I introduced the model in parameters, thanks to model binding request's content were being read and parsed into model, so when I forward request to another API I send request without content. The fix is to remove all parameters:
[HttpPut]
public Task<HttpResponseMessage> Create()
{
return ForwardRequestToSomeApi();
}

HttpContext.Current.Session and UmbracoContext.Current.Session is always null in Umbraco

I am using Umbraco 7.5.7 for my application When ever I click on the content item in CMS it shows me this error, I have provided the code below, can some help me on this.
HttpContext.Current.Session and UmbracoContext.Current.HttpContext.Session is always null in Umbraco CMS while accessing content and throwing
Received an error from the server
-"value cannot be null. Parameter Name: httpSessionState" error on the cms UI
IManageState.cs
public interface IManageState
{
void SetValue(string key, object data);
bool HasKey(string key);
T GetValue<T>(string key);
bool SessionIdExists();
}
SessionContext.cs
protected readonly IManageState SessionManager;
public SessionContext()
{
SessionManager = new HttpSessionManager();
}
HttpSessionManager.cs
public class HttpSessionManager : IManageState
{
private readonly HttpSessionStateBase _session;
public HttpSessionManager()
{
}
public HttpSessionManager(HttpSessionStateBase session)
{
_session = session;
}
public HttpSessionStateBase Session
{
get { return _session ?? new HttpSessionStateWrapper(HttpContext.Current.Session); }//getting null here for HttpContext.Current.Session
}
public void SetValue(string key, object data)
{
Session[key] = data;
}
public bool HasKey(string key)
{
return Session[key] != null;
}
public T GetValue<T>(string key)
{
return HasKey(key) ? (T)Session[key] : default(T);
}
public bool SessionIdExists()
{
if (HttpContext.Current.Session == null)
{
return false;
}
string cookieHeader = HttpContext.Current.Request.Headers[GenericConstants.Cookie];
return !string.IsNullOrEmpty(cookieHeader)
&& cookieHeader.IndexOf(GenericConstants.AuthorizationCode, StringComparison.OrdinalIgnoreCase) >= 0
&& HttpContext.Current.Request.Cookies[GenericConstants.DOTNETSESSIONID] != null
&& Session[GenericConstants.AuthorizationCode] != null
&& HttpContext.Current.Request.Cookies[GenericConstants.AuthorizationCode] == Session[GenericConstants.AuthorizationCode];
}
}
I have also tried the below code, I replaced this line
get { return _session ?? new HttpSessionStateWrapper(HttpContext.Current.Session); }
with
get { return _session != null ? _session : HttpContext.Current.Session != null ? new HttpSessionStateWrapper(HttpContext.Current.Session): UmbracoContext.Current.HttpContext.Session ; }
StackTrace
at System.Web.HttpSessionStateWrapper..ctor(HttpSessionState httpSessionState)
at MyProject.Infrastructure.Services.HttpSessionManager.get_Session() in D:\MyProject\MyProject.Infrastructure\Services\HttpSessionManager.cs:line 50
at MyProject.Infrastructure.Services.HttpSessionManager.HasKey(String key) in D:\MyProject\MyProject.Infrastructure\Services\HttpSessionManager.cs:line 74
at MyProject.Infrastructure.Services.HttpSessionManager.GetValue[T](String key) in D:\MyProject\MyProject.Infrastructure\Services\HttpSessionManager.cs:line 123
at MyProject.Web.Http.SessionContext.get_IsAuthenticated() in D:\MyProject\MyProject.Web\Http\SessionContext.cs:line 125
at ASP._Page_Views_MacroPartials_Dashboard_cshtml.Execute() in d:\MyProject\MyProject.Web\Views\MacroPartials\Dashboard.cshtml:line 7
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at Umbraco.Core.Profiling.ProfilingView.Render(ViewContext viewContext, TextWriter writer)
at Umbraco.Web.Mvc.ControllerExtensions.RenderViewResultAsString(ControllerBase controller, ViewResultBase viewResult)
at Umbraco.Web.Macros.PartialViewMacroEngine.Execute(MacroModel macro, IPublishedContent content)
at Umbraco.Web.Macros.PartialViewMacroEngine.Execute(MacroModel macro, INode node)
at umbraco.macro.LoadPartialViewMacro(MacroModel macro)
at umbraco.macro.renderMacro(Hashtable pageElements, Int32 pageId)
at Umbraco.Web.UmbracoComponentRenderer.RenderMacro(macro m, IDictionary`2 parameters, page umbracoPage)
at Umbraco.Web.Editors.MacroController.GetMacroResultAsHtml(String macroAlias, Int32 pageId, IDictionary`2 macroParams)
at Umbraco.Web.Editors.MacroController.GetMacroResultAsHtmlForEditor(MacroParameterModel model)
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

ASP.NET Core ViewComponent Invocation: InvalidCastException

Here is what I have
I have a view component as
public class TestViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(int param1, int param2)
{
return Content(param1.ToString() + param2);
}
}
And a controller as
public class HomeController : Controller
{
private Dictionary<string, object> _dict = new Dictionary<string, object>();
public IActionResult Index()
{
_dict = new Dictionary<string, object>() { ["param1"] = 100, ["param2"] = 200 };
return ViewComponent("Test", _dict)
}
public IActionResult Index1()
{
var obj = new { param1 = 100, param2 = 200 };
var objString = JsonConvert.SerializeObject(obj);
_dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(objString);
return ViewComponent("Test", _dict);
}
}
When I call the first Index action everything is good. It works as expected but when I call the Index1 action I get an error with the following stack trace
System.InvalidCastException: Unable to cast object of type 'System.Int64' to type 'System.Int32'.
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.ViewComponents.DefaultViewComponentInvoker.<InvokeAsyncCore>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.ViewComponents.DefaultViewComponentInvoker.<InvokeAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.ViewComponents.DefaultViewComponentHelper.<InvokeCoreAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewComponentResultExecutor.<ExecuteAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeResultAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResultFilterAsync>d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResultExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__6.MoveNext()
It seems there is some issue after the Deserialization. The exception is thrown even before the InvokeAsync method of the view component is called.
I have been stuck on this for a while. Any help will be really appreciated.
Thanks.
The error message is pretty much telling what's happening here. The actual objects in the deserialized dictionary are Int64s, which the arguments expected by the ViewComponent are Int32 (also called int in C#).

Categories