#HhtmlDropdown throw SerializationException Exception - asp.net-mvc-4

I have a form that has a DropDownList. I am using SQLServer State mode to save the session in SQL Server. The form is displayed correctly; however, it throws an exception during the form submission. I've been looking and tried some of the suggested answer that were posted online with no luck. What am I doing wrong here?
//This is the section where I am building the SelectList Item in the controller
var ListDepartment = ManageUsersMembership.GetDepartment(SessionWrapper.studentBookTrade.SelectedSchoolID);
// book.DepartmentList = ListDepartment; //new SelectList(ListDepartment, "DepartmentID", "DepartmentName", SessionWrapper.studentBookTrade.SelectedDepartmentID);
List<SelectListItem> lDepartment = new List<SelectListItem>();
foreach (var item in ListDepartment)
{
if (SessionWrapper.studentBookTrade.SelectedDepartmentID > 0 && item.DepartmentID == SessionWrapper.studentBookTrade.SelectedDepartmentID)
{
lDepartment.Add(new SelectListItem { Text = item.DepartmentName, Value = item.DepartmentID.ToString(), Selected = true });
}
else
{
lDepartment.Add(new SelectListItem { Text = item.DepartmentName, Value = item.DepartmentID.ToString() });
}
}
book.DepartmentList = lDepartment;
//this is my property in the Model:
public virtual IEnumerable<SelectListItem> DepartmentList { get; set; }
//This is the HTML Code in my View:
#Html.DropDownListFor(model => model.DepartmentID, new SelectList(Model.DepartmentList, "Value", "Text"), "Select Department", new {#class="form-control", id="DepartmentID", onchange = "ValueSelected()" })
#Html.ValidationMessageFor(model => model.DepartmentID)
//The exception
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.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: 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.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SerializationException: Type 'System.Web.Mvc.SelectList' in Assembly 'System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +10751795
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(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder) +185
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) +565
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +446
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.SqlSessionStateStore.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) +135
System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +565
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

I think you have too much here. Try changing your code this way
public IEnumerable<SelectListItem> DepartmentList { get; set; }
I usually use List but ienumerable should work too
then on your view you don't need to cast the list
#Html.DropDownListFor(model => model.DepartmentID, Model.DepartmentList, "Select Department", new {#class="form-control", id="DepartmentID", onchange = "ValueSelected()" })
the "for" helper will map the list for you. See if this helps

Related

Ignore AuthenticationContext In SAML2 Response

We have an asp.net 5 web app that will serve as a Service Provider to our users.
We have chosen ITfoxtec Identity SAML 2.0 library for this purpose.
The request is successful, but in the response we get the following error:
System.ArgumentException: IDX13300: 'System.String' must be an absolute Uri, was: 'System.Uri'
For completeness here is the full stack trace:
Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenReadException: IDX13102: Exception thrown while reading 'System.String' for Saml2SecurityToken. Inner exception: 'System.ArgumentException'.
---> System.ArgumentException: IDX13300: 'System.String' must be an absolute Uri, was: 'System.Uri'
at Microsoft.IdentityModel.Tokens.Saml2.Saml2AuthenticationContext.set_DeclarationReference(Uri value)
at Microsoft.IdentityModel.Tokens.Saml2.Saml2Serializer.ReadAuthenticationContext(XmlDictionaryReader reader)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Tokens.Saml2.Saml2Serializer.ReadAuthenticationContext(XmlDictionaryReader reader)
at Microsoft.IdentityModel.Tokens.Saml2.Saml2Serializer.ReadAuthenticationStatement(XmlDictionaryReader reader)
at Microsoft.IdentityModel.Tokens.Saml2.Saml2Serializer.ReadAssertion(XmlReader reader)
at Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ReadSaml2Token(XmlReader reader)
at Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ReadSaml2Token(String token)
at ITfoxtec.Identity.Saml2.Saml2AuthnResponse.ReadSecurityToken(String tokenString)
at ITfoxtec.Identity.Saml2.Saml2AuthnResponse.Read(String xml, Boolean validateXmlSignature)
at ITfoxtec.Identity.Saml2.Saml2PostBinding.Read(HttpRequest request, Saml2Request saml2RequestResponse, String messageName, Boolean validateXmlSignature)
at ITfoxtec.Identity.Saml2.Saml2Binding1.ReadSamlResponse(HttpRequest request, Saml2Response saml2Response)
at SsoGovILApi.Controllers.SamlController.AssertionConsumerService() in F:\Dev\ashilon\SsoGovIlApi\Controllers\SamlController.cs:line 45
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Builder.Extensions.UsePathBaseMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT1.ProcessRequestAsync()
I have looked up the error and found that the authentication context can be ignored, and some libraries give this option, like this one for example:
IgnoreAuthenticationContextInResponse compatibility flag
Is there a way to this in the ITfoxtec library too?
Thanks in advance,
ashilon
You can implement you own version of Saml2AuthnResponse and on the Saml2SecurityTokenHandler property set your own implementation of Saml2ResponseSecurityTokenHandler.
I think it should be possible to change the authentication context validation in your own implementation of the Saml2ResponseSecurityTokenHandler.
I ran into the same issue myself, also with an Idp that sent a non compliant AuthnContextClassRef.
At least with .net core it's possible to avoid the error with a minimal change in Saml2AuthnResponse without needing a custom Saml2ResponseSecurityTokenHandler:
The tokenstring passed to ReadSecuritytoken/ReadClaimsIdentity can be safely modified without impacting signature verification. Modified Read method in Saml2AuthnResponse:
var tokenString = assertionElement.OuterXml;
if (this.TokenProcessor != null)
{
tokenString = this.TokenProcessor.ProcessToken(tokenString);
}
Saml2SecurityToken = ReadSecurityToken(tokenString);
ClaimsIdentity = ReadClaimsIdentity(tokenString, detectReplayedTokens);
Providing a property for a method to manipulate the tokenString works just fine. Implementing my own Saml2AuthnResponse seems a bit overkill and creating a derived class that just replaces the read method does not seem to be viable due to the protection level.
As a simple workaround for this problem, what I did was to simply remove the saml:AuthnContextDeclRef element from the response's xml.
Here's the code, in POC state, before cleaning up:
public async Task<IActionResult> AssertionConsumerService()
{
var binding = new Saml2PostBinding();
var saml2AuthnResponse = new Saml2AuthnResponse(_config);
var httpRequest = Request.ToGenericHttpRequest();
// Remove AuthnContextDeclRef element
var samlResponseXml = Encoding.UTF8.GetString(Convert.FromBase64String(httpRequest.Form["SAMLResponse"] ?? string.Empty));
var root = XElement.Parse(samlResponseXml);
XNamespace ns = "urn:oasis:names:tc:SAML:2.0:assertion";
root.Element(ns + "Assertion")?.Element(ns + "AuthnStatement")?.Element(ns + "AuthnContext")?.Element(ns + "AuthnContextDeclRef")?.Remove();
httpRequest.Form["SAMLResponse"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(root.ToString()));
binding.ReadSamlResponse(httpRequest, saml2AuthnResponse);
if (saml2AuthnResponse.Status != Saml2StatusCodes.Success)
{
throw new AuthenticationException($"SAML Response status: {saml2AuthnResponse.Status}");
}
binding.Unbind(httpRequest, saml2AuthnResponse);
await saml2AuthnResponse.CreateSession(HttpContext, claimsTransform: ClaimsTransform.Transform);
var relayStateQuery = binding.GetRelayStateQuery();
var returnUrl = relayStateQuery.ContainsKey(RelayStateReturnUrl) ? relayStateQuery[RelayStateReturnUrl] : Url.Content("~/");
return Redirect(returnUrl);
}

ViewDataDictionary model is correct, failing when calling RenderPartial

I am porting a .NET MVC application to .NET Core. The issue is occurring when rendering a partial using Html.RenderPartial.
The relevant code is:
<div class="row">
<h2>#WebResources.OtherUsersSavedItems</h2>
#foreach (var item in Model.OtherUsersSavedItems)
{
Html.RenderPartial("SavedItem", Html.ViewDataDictionaryFrom(new { IsLink = true }, item));
}
</div>
The OtherUsersSavedItems property on the model is defined as SavedItem[]. There is an identical call to RenderPartial earlier in my view, which works, but the difference is that it's not using a custom ViewDataDictionary:
<div class="row">
<h2>#WebResources.SavedItems</h2>
#foreach (var item in Model.SavedItems)
{
Html.RenderPartial("SavedItem", item);
}
</div>
The code to ViewDataDictionaryFrom is as follows:
public static ViewDataDictionary ViewDataDictionaryFrom(this IHtmlHelper helper, object dictionary, object model = null)
{
if (dictionary == null)
return null;
// Convert the object to a ViewDataDictionary
ViewDataDictionary vdd = new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary());
foreach (var property in dictionary.GetType().GetProperties())
vdd.Add(property.Name, property.GetValue(dictionary));
vdd.Model = model;
return vdd;
}
The previous code, when running under .NET MVC was using the RenderPartialExtensions.RenderPartial(HtmlHelper, Strink, Object, ViewDataDictionary) overload and that was working fine. There was one change between .NET MVC and .NET Core for the ViewDataDictionaryFrom method, which was to add the model and set it accordingly (vdd.Model = model) to try and work around the missing overload in .NET Core.
The exception I receive is InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'MyApplication.Models.ListModel', but this ViewDataDictionary instance requires a model item of type 'MyApplication.Models.SavedItem'. Note that ListModel is the of the parent view.
The stack frames (truncated, starting at the line in my code which fails) is:
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(object
value)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary..ctor(ViewDataDictionary
source, object model, Type declaredModelType) lambda_method(Closure ,
ViewDataDictionary )
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorPagePropertyActivator.CreateViewDataDictionary(ViewContext
context)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorPagePropertyActivator.Activate(object
page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorPageActivator.Activate(IRazorPage
page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView+d__16.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)
Microsoft.AspNetCore.Mvc.Razor.RazorView+d__15.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Mvc.Razor.RazorView+d__14.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)
Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper+d__60.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)
Microsoft.AspNetCore.Mvc.Rendering.HtmlHelperPartialExtensions.RenderPartial(IHtmlHelper
htmlHelper, string partialViewName, ViewDataDictionary viewData)
AspNetCore._Views_Index_cshtml+d__0.MoveNext()
in Index.cshtml
Html.RenderPartial("SavedItem", Html.ViewDataDictionaryFrom(new { IsLink = true }, item));
I went and looked at the source code available on GitHub. The overload
public static void RenderPartial(
this IHtmlHelper htmlHelper,
string partialViewName,
ViewDataDictionary viewData)
Is a wrapper around RenderPartialAsync which invokes it with the current model, ignoring what is in the ViewDataDictionary that is passed in.
To correct my issue, I use the RenderPartialAsync method in my Razor view, which allows me to specify both the ViewDataDictionary and the model.

dryioc controller.service is resolved during setup, not during api call

I have been searching a lot, both online, and debugging, re-read docs for dryioc and took a look at the samples. I don't think my issues lies with dryioc, or maybe I'm overlooking a silly mistake.
Project setup => service => owin + webapi2
Using attributerouting, swagger and apiversioning
This is how I setup my container
private IContainer SetupDependencyInjection(HttpConfiguration config)
{
var container = new Container();
container.WithWebApi(config, throwIfUnresolved: type => typeIsController());
container.RegisterWebApiControllers(config);
container.Register<IObjectFactory, ObjectFactory>(Reuse.Singleton);
RegisterStoreServices(container);
RegisterMetadata(container);
var validate = container.Validate();
var verify = container.VerifyResolutions();
if (validate.Any() || verify.Any())
{
throw new Exception("Error occured while setting up service dependencies.");
}
using (var c = container.OpenScope(Reuse.WebRequestScopeName))
{
var songController = c.Resolve<Musify.WebApi.Controllers.v1._0.SongsController>();
var GenresController = c.Resolve<Musify.WebApi.Controllers.v1._0.GenresController>();
}
return container;
}
Both RegisterStoreServices and RegisterMetadata only contain singleton or transient registrations.
When I try to call a controller method on my API controller, I get the following error
{
"message": "An error has occurred.",
"exceptionMessage": "An error occurred when trying to create a controller of type 'SongsController'. Make sure that the controller has a parameterless public constructor.",
"exceptionType": "System.InvalidOperationException",
"stackTrace": " at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"innerException": {
"message": "An error has occurred.",
"exceptionMessage": "Unable to resolve Musify.Api.Service.Data.ISongRepository as parameter \"songRepository\"\r\n in scoped Musify.WebApi.Controllers.v1._0.SongsController.\r\nWhere no service registrations found\r\n and number of Rules.FallbackContainers: 0\r\n and number of Rules.UnknownServiceResolvers: 0",
"exceptionType": "DryIoc.ContainerException",
"stackTrace": " at DryIoc.Throw.It(Int32 error, Object arg0, Object arg1, Object arg2, Object arg3)\r\n at DryIoc.Container.ThrowUnableToResolve(Request request)\r\n at DryIoc.Container.DryIoc.IContainer.ResolveFactory(Request request)\r\n at DryIoc.ReflectionFactory.CreateExpressionOrDefault(Request request)\r\n at DryIoc.Factory.GetExpressionOrDefault(Request request)\r\n at DryIoc.Factory.GetDelegateOrDefault(Request request)\r\n at DryIoc.Container.ResolveAndCacheDefaultDelegate(Type serviceType, Boolean ifUnresolvedReturnDefault, IScope scope)\r\n at DryIoc.Container.DryIoc.IResolver.Resolve(Type serviceType, Boolean ifUnresolvedReturnDefault)\r\n at DryIoc.WebApi.DryIocDependencyScope.GetService(Type serviceType)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
}
}
I know that in a lot of cases, this is because the service is not registered, but I did.
container.Register<ISongRepository, SongRepository>(Reuse.Singleton);
As you can see in the fist code snippet, I valide, verify, and I even tried container.openscope, to see if the container was registered. And on the container, I can see the songrepository being filled in as well.
So I'm guessing, somehow, the webapi doesn't use the controllers inujected into the container.
Am I doing something wrong in my dependency setup?
public void Configuration(IAppBuilder appBuilder)
{
SetupLogging();
var config = new HttpConfiguration();
SetupRouting(config);
SetupVersioning(config);
SetupJson(config);
SetupDocumentation(config);
SetupDependencyInjection(config);
appBuilder.UseWebApi(config);
appBuilder.UseErrorPage(ErrorPageOptions.ShowAll);
}
I'm not sure if it matters, but I'm setting the container up, after everything else has been configured.
After some messing around, I got it working after adding the lines marked with //this
var container = SetupDependencyInjection(config);
appBuilder.UseDryIocOwinMiddleware(container); //this
appBuilder.UseWebApi(config);
appBuilder.UseDryIocWebApi(config); //this
I would like an explenation though, if someone could give me one.
Because on another post, I read that a guy had problems because of using both UseWebApi and UseDryIocWebApi.
But without the OwinMiddleware, it still wouldn't work. So what do both of these functions accomplish?
Or did I use a "wrong fix"?

Unexpected Error Occurred ServiceStack Redis Client

Am getting an error while manipulating Hashes with Servicestack pooled redisClientsManager.
here is how i have registered the IOC
private static IRedisClientsManager redisClientsManager;
redisClientsManager = new PooledRedisClientManager("host:6379");
container.Register<IRedisClientsManager>(c => redisClientsManager);
container.Register(c => c.Resolve<IRedisClientsManager>().GetClient());
container.Register<IRepository>(c => new Repository(c.Resolve<IRedisClientsManager>()));
And Here is how am using it in Repository,
IRedisClientsManager manager;
public repository(IRedisClientsManager mgr)
{
this.manager=mgr;
}
//Method to talk to redis
using(var red = manager.getClient())
{
//do stuff with Other datatype except Hashes WORKS
}
//Error raised here
using(var redHash = manager.getClient())
{
//do stuff with Hashes DOESNT WORKS
}
Error:
Unexpected Error:* 0...., Redis response Error
Any Suggestions on how to use PooledRedisClientManager Threadsafe.!
Adding Stack trace :
Message:Unexpected reply: *0, sPort: 6379, LastCommand:
at ServiceStack.Redis.RedisNativeClient.CreateResponseError(String error)
at ServiceStack.Redis.RedisNativeClient.ParseSingleLine(String r)
at ServiceStack.Redis.RedisNativeClient.SendExpectData(Byte[][] cmdWithBinaryArgs)
at ServiceStack.Redis.RedisNativeClient.EvalShaStr(String sha1, Int32 numberKeysInArgs, Byte[][] keys)
at ServiceStack.Redis.RedisClient.ExecLuaShaAsString(String sha1, String[] keys, String[] args)
at Services.Data.Repository.GetMo(geoJ , DateTime , String ) in \Data\Repository.cs:line 169
at Services.Api.getMService.Any(getM request) in \Api\getMService.cs:line 15
at lambda_method(Closure , Object , Object )
at ServiceStack.ServiceHost.ServiceRunner`1.Execute(IRequestContext requestContext, Object instance, TRequest request)
When you get an Message:Unexpected reply Error when calling a LUA script you need to ensure that what the script is returning matches with the RedisClient API you're calling, which in this case of RedisClient.ExecLuaShaAsString() expects a string.
If you're unsure of what Type your LUA script returns you can call the more reusable ExecLuaSha which returns a complex RedisText type that can support a number of different LUA response types.

Sorry, an error occurred while processing your request. in MVC3 Model Entities [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
I am new in MVC, made an app that works on my local machine (Windows 7 with SQLExpress) but when I deploy live on Windows 2008 R2, SQL 2008 R2 and IIS7, I get this error: "Sorry, an error occurred while processing your request"
Below are snippets of the code in question:
WEB.CONFIG connectionStrings
add name="RentalEntities" connectionString="Data Source=[ServerName];Initial Catalog=[DatabaseName];Integrated Security=True" providerName="System.Data.SqlClient"
HOMECONTROLLER
namespace Rental.Controllers
{
RentalEntities rentalDB = new RentalEntities();
...
public ActionResult Index()
{
var listings = from l in rentalDB.Listings select l;
return View(listings.ToList());
}
}
HOME/INDEX.CSHTML
#model List<Rental.Models.Listing>
#foreach (var listing in Model)
{
#listing.ListingName <br />
}
The error occurred on this line #foreach (var listing in Model), something to do with being null - note that NONE of the fields in the database are null. Any help will be appreciated.
Below is the full error message: [ where line 13 is: foreach (var listing in Model)
Sorry, an error occurred while processing your request.
System.NullReferenceException: Object reference not set to an instance of an object. at ASP._Page_Views_Home_Index_cshtml.Execute() in c:\inetpub\wwwroot\projects\Rentals\Views\Home\Index.cshtml:line 13 at System.Web.WebPages.WebPageBase.ExecutePageHierarchy() at System.Web.Mvc.WebViewPage.ExecutePageHierarchy() at System.Web.WebPages.StartPage.ExecutePageHierarchy() at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
What has happened here is that you've passed a null value into the Model for index.cshtml.
The code is foreach'ing over null.
Debugging this in Prod:
How many rows are in the Listing table on the Prod server?
Does your LINQ To SQL .dbml refer exactly to the connection string in your web.config, or does it have a hidden connection string buried within the .designer.cs?
Try setting up some debug info on INDEX.CSHTML
#(Model==null) //will write to page whether the model data being passed is null.
Debugging this in Dev/Test:
To help debug why it's null, set a breakpoint for yourself on the line in Index(). Set it on return View(listings.ToList());. Is it actually null? Then set a breakpoint on the check for null in your View.
Before foreach, run a check for null:
#if (Model != null)
{
foreach (var foo in Model)
{
//your code
}
}
else
{
#: Model Is null!
}