Exception in mvc.net controller - asp.net-mvc

In mvc .net c# i have over loaded OnException action in my base controller
In controller action I have generated zip file using Ionic.Zip.dll
The code for this is like
foreach (var file in filesToarchive)
{
zip.AddFile(#file.FilePath);
}
zip.Save(Response.OutputStream);
var rept = reports.First();
return File(Response.OutputStream, "plain/zip", "abc.zip");
While downloading the file it throws exception in OnException action in base controller
the exception is :
System.Web.HttpResponseStream.Read(Byte[]
buffer, Int32 offset, Int32 count)
at
System.Web.Mvc.FileStreamResult.WriteFile(HttpResponseBase
response) at
System.Web.Mvc.FileResult.ExecuteResult(ControllerContext
context) at
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult
actionResult) at
System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass14.b__11()
at
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext
preContext, Func1 continuation) at
System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass14.<>c__DisplayClass16.<InvokeActionResultWithFilters>b__13()
at
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
controllerContext, IList1 filters,
ActionResult actionResult) at
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
If anybody has any solution then please give it to me.
Thanks

Try using a memory stream instead of writing to the response:
using (var stream = new MemoryStream())
{
zip.Save(stream);
return File(stream.ToArray(), "plain/zip", "abc.zip");
}
Also I've removed the var rept = reports.First(); line as I don't see any relevance to the code snippet you've posted.

Related

Mono HttpWebRequest Post Data Incomplete

I am posting data from the MonoTouch client to my Asp.Net MVC Controller. However, sometimes I can the following error:
System.ArgumentException: Unterminated string passed in. (49152):
.....LONG JSON STRING WHICH IS MISSING THE END **" }** and possible other characters.
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeString()
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
at System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext)
at System.Web.Mvc.ValueProviderFactoryCollection.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext)
at System.Web.Mvc.ControllerBase.get_ValueProvider()
at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
I was wondering is there any scenario where the HttpWebRequest object in Mono would cut off the request daya, not posting all of it?
The code in Mono is HttpRequest.BeginGetResponse(), which is an async operation.

NullReferenceException in WebConfigScopeDictionary

Occasionally (about once a month) an ASP.NET MVC 3 web application fails with this exception.
System.NullReferenceException: Object reference not set to an instance of an object.
Server stack trace:
at System.Collections.Specialized.NameObjectCollectionBase.BaseGetAllKeys()
at System.Collections.Specialized.NameValueCollection.get_AllKeys()
at System.Web.WebPages.Scope.WebConfigScopeDictionary.<>c__DisplayClass4.<.ctor>b__0()
at System.Lazy`1.CreateValue()
Exception rethrown at [0]:
at System.Lazy`1.get_Value()
at System.Web.WebPages.Scope.WebConfigScopeDictionary.TryGetValue(Object key, Object& value)
at System.Web.Mvc.ViewContext.ScopeGet[TValue](IDictionary`2 scope, String name, TValue defaultValue)
at System.Web.Mvc.ViewContext.ScopeCache..ctor(IDictionary`2 scope)
at System.Web.Mvc.ViewContext.ScopeCache.Get(IDictionary`2 scope, HttpContextBase httpContext)
at System.Web.Mvc.ViewContext.GetClientValidationEnabled(IDictionary`2 scope, HttpContextBase httpContext)
at System.Web.Mvc.Html.FormExtensions.FormHelper(HtmlHelper htmlHelper, String formAction, FormMethod method, IDictionary`2 htmlAttributes)
at ASP._Page_Views_mywebpage_Create_cshtml.Execute() in c:\App\Views\Mywebpage\Create.cshtml:line 11
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)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
This exception occurs on a line with
#using (Html.BeginForm())
From the moment this exception occurs once, the application is unusable. Every view will start throwing this error. I've looked around in the source code but seem unable to find anything. There are people who experience the same behaviour but with a different error and or by different code.
When digging deeper in the source of WebConfigScopeDictionary you can see that the AppSettings are being read:
public WebConfigScopeDictionary() : this(WebConfigurationManager.AppSettings)
{
}
public WebConfigScopeDictionary(NameValueCollection appSettings)
{
this._items = new Lazy<Dictionary<object, object>>(() => appSettings.AllKeys.ToDictionary((string key) => key, (string key) => appSettings[key], ScopeStorageComparer.Instance));
}
The appsettings come from the ConfigurationManager:
public static NameValueCollection AppSettings
{
get
{
object section = ConfigurationManager.GetSection("appSettings");
if (section == null || !(section is NameValueCollection))
{
throw new ConfigurationErrorsException(SR.GetString("Config_appsettings_declaration_invalid"));
}
return (NameValueCollection)section;
}
}
If there would be a problem with the web.config this code should have thrown an exception. But it doesn't. Eventually count is called on the collection that is returned by the AppSettings property. Since it is probably null at this point it throws.
protected string[] BaseGetAllKeys()
{
int count = this._entriesArray.Count;
string[] array = new string[count];
for (int i = 0; i < count; i++)
{
array[i] = this.BaseGetKey(i);
}
return array;
}
If anyone has any ideas, feel free to share.
After enquiring with the ops team it would appear that the application pool was being recycled after the timed interval had expired. This happened during office hours while the application is under a significant load. We've now changed it to recycle at a specific time, which is still a workaround but should prevent the problem from occurring too frequently.

PartialView as string + JsonResult

I'm just looking for a nice way how to return JSON object from server that contains html of partial view and some additional data if needed.
I'm using approach by Tim Scott to render partialview as string (with some modifications - made it to be viewenginescollection aware, made it to understand difference between view and partial view, put it into StringResult class and wrapped around with controller extension method).
Here's what causes trouble:
public static string RenderViewToString(ControllerContext controllerContext,
IView view, ViewDataDictionary viewData, TempDataDictionary tempData)
{
Stream filter = null;
ViewPage viewPage =
new ViewPage
{
ViewContext = new ViewContext
(controllerContext, view, viewData, tempData)
};
//Right, create our view
//Get the response context, flush it and get the response filter.
var response = viewPage.ViewContext.HttpContext.Response;
response.Flush();
var oldFilter = response.Filter;
try {
//Put a new filter into the response
filter = new MemoryStream();
response.Filter = filter;
//Now render the view into the memorystream and flush the response
viewPage.ViewContext.View.Render(viewPage.ViewContext, viewPage.ViewContext.HttpContext.Response.Output);
response.Flush();
//Now read the rendered view.
filter.Position = 0;
var reader = new StreamReader(filter, response.ContentEncoding);
return reader.ReadToEnd();
}
finally {
//Clean up.
if (filter != null) {
filter.Dispose();
}
//Now replace the response filter
response.Filter = oldFilter;
}
}
usage looks like this:
var v = this.ViewResultToString(PartialView("_Foo", foo));
return Json(new {Html = Server.HtmlEncode(v), Bar = foo.Bar});
However - this throws an exception:
Server cannot set content type after HTTP headers have been sent.
Here's a stack trace:
[HttpException (0x80004005): Server cannot set content type after HTTP headers have been sent.]
System.Web.HttpResponse.set_ContentType(String value) +8760264
System.Web.HttpResponseWrapper.set_ContentType(String value) +11
System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +131
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +10
System.Web.Mvc.<>c__DisplayClass11.b__e() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation) +255
System.Web.Mvc.<>c__DisplayClass13.<InvokeActionResultWithFilters>b__10() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList1 filters, ActionResult actionResult) +179
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +395
System.Web.Mvc.Controller.ExecuteCore() +123
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
Company.UI.Project.Controllers.Base.BaseController.Execute(RequestContext requestContext) in c:\Project\Controllers\Base\BaseController.cs:109
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +144
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Thing is - whenever i call RenderViewToString, an exception will be thrown if I'm going to return any other ActionResult that's not ContentResult.
So - is there another nice way how to serialize anonymous object into Json without 3rd party tools
OR
how to make this approach to work (how to kill that damn exception,
what exactly forces those headers to be sent)?
Got it working using this.
This was the problem:
In the first case, intercepting the output to HttpResponse using a "capturing filter" forces you to flush the output before the whole view is rendered and, since the original HttpResponse object is used, doesn't allow you to change content encoding, mime type or add headers after the partial view has been rendered.
Solution - not to use 'flushing' technique to render partial view.
Seems to me like your RenderViewToString should be creating a ViewUserControl rather than a ViewPage.
Do note that what you're doing will make the OnResultExecuting on any Action filters happen after the view is rendered!

On $.Post in Json used in ASP.NET MVC 1.0 i am getting exceed maxlength error

i am getting this error given below i guess its a max length exceed error when i call a action in a controller using $.post method can you tell me what setting should i put to increase the length
System.InvalidOperationException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat)
at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat)
at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj)
at System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass11.b__e()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass11.<>c__DisplayClass13.<InvokeActionResultWithFilters>b__10()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass11.<>c__DisplayClass13.b__10()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext)
at System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Thank you in advance
You can set it in the web.config for unlimited, the following way:
<Scripting>
<WebServices>
<JsonSerialization MaxJsonLength="0" />
</WebServices>
</Scripting>
The default value is around 4MB.
msdn link
Here's a very good blog post about it
http://brianreiter.org/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/

MVC Model issue can you diagnose what this is saying?

This is part of the first build repoistory that sits on Microsoft MVC.
First call from the controller down for model.
public ActionResult Index()
{
var prog = yRepository.FindUpComingProgrammes();
return View(prog);
}
ASP ERROR:
Server Error in '/' Application.
--------------------------------------------------------------------------------
The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[Code.Models.Prog]' but this dictionary requires a model item of type 'Code.Models.Prog'.
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.InvalidOperationException: The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[Code.Models.Prog]' but this dictionary requires a model item of type 'Code.Models.Prog'.
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:
[InvalidOperationException: The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[Code.Models.Prog]' but this dictionary requires a model item of type 'Code.Models.Prog'.]
System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +116376
System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +369
System.Web.Mvc.ViewPage`1.SetViewData(ViewDataDictionary viewData) +59
System.Web.Mvc.WebFormView.RenderViewPage(ViewContext context, ViewPage page) +70
System.Web.Mvc.WebFormView.Render(ViewContext viewContext, TextWriter writer) +92
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +278
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +10
System.Web.Mvc.<>c__DisplayClass11.<InvokeActionResultWithFilters>b__e() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +251
System.Web.Mvc.<>c__DisplayClass13.<InvokeActionResultWithFilters>b__10() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +178
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +399
System.Web.Mvc.Controller.ExecuteCore() +126
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +27
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +151
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +57
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
It sounds like you are using a strongly typed view and the object being passed to the view is not the same that type that the view is bound to...

Resources