I am trying to return a csv file from an MVC Controller derived from a List. I came up with the following code for controller based on combining what I read from docs and SO questions. I must be missing something because I am getting yellow screen of death with "Cannot access a closed stream"...
public class ConsumersFileController : Controller
{
private readonly TDCContext _db = new TDCContext();
public ActionResult Index()
{
IEnumerable<Consumer> list = _db.Consumers.ToList();
//put List in memory stream object
MemoryStream memoryStream = new MemoryStream();
using (memoryStream)
{
//return memory stream as file stream result:
using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, System.Text.Encoding.UTF8, true))
{
foreach (var item in list)
{
var itemBytes = item.Serialize();
binaryWriter.Write(itemBytes.Length);
binaryWriter.Write(itemBytes);
}
FileStreamResult fileStream =
new FileStreamResult(memoryStream, "application/txt") {FileDownloadName = "zips.csv"};
return fileStream;
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
Here is the stack trace:
[ObjectDisposedException: Cannot access a closed Stream.]
System.IO.__Error.StreamIsClosed() +59
System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count) +14731549
System.Web.Mvc.FileStreamResult.WriteFile(HttpResponseBase response) +93
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +88
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +831
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +81
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +43
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +607
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +134
How can the stream get closed if I am returning the result inside the using block of the stream?
You should remove:
using (memoryStream)
FileStreamResult will dispose memoryStream for you.
The reason that your code doesn't work is that the actual work that reads from memoryStream is not in your code - it is in MVC code that calls fileStream.WriteFile. But that code is executed somewhere higher up the call stack. And by the time WriteFile is called (which needs memoryStream) you have already disposed it.
Related
I am using visual studio 2019.
I have a problem which I haven't encountered before - in view, this line (just this line) is throwing error:
#Scripts.Render("~/scripts/scriptCommon")
I've checked bundles config:
ScriptBundle scriptCommon = new ScriptBundle("~/scripts/scriptCommon");
scriptCommon.Include("~/static/scripts/jquery-1.11.0.min.js");
scriptCommon.Include("~/static/scripts/bootstrap.min.js");
Both files are on the file system.
This bundle is also added to bundles with:
bundles.Add(scriptCommon);
(just like all the other bundles)
I don't understand why this error? What could be the reason?
Short error message:
System.NullReferenceException: Object reference not set to an instance of an object.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.Ajax.Utilities.ActivationObject.DefineField(INameDeclaration nameDecl, FunctionObject fieldValue) +20
Microsoft.Ajax.Utilities.ActivationObject.DefineLexicalDeclarations() +92
Microsoft.Ajax.Utilities.BlockScope.DeclareScope() +4
Microsoft.Ajax.Utilities.ResolutionVisitor.CreateFields(ActivationObject scope) +35
Microsoft.Ajax.Utilities.ResolutionVisitor.CreateFields(ActivationObject scope) +77
Microsoft.Ajax.Utilities.ResolutionVisitor.CreateFields(ActivationObject scope) +77
Microsoft.Ajax.Utilities.ResolutionVisitor.CreateFields(ActivationObject scope) +77
Microsoft.Ajax.Utilities.ResolutionVisitor.Apply(AstNode node, ActivationObject scope, CodeSettings settings) +62
Microsoft.Ajax.Utilities.JSParser.Parse(CodeSettings settings) +972
Microsoft.Ajax.Utilities.Minifier.MinifyJavaScript(String source, CodeSettings codeSettings) +548
System.Web.Optimization.JsMinify.Process(BundleContext context, BundleResponse response) +92
System.Web.Optimization.Bundle.ApplyTransforms(BundleContext context, String bundleContent, IEnumerable`1 bundleFiles) +273
System.Web.Optimization.Bundle.GenerateBundleResponse(BundleContext context) +141
System.Web.Optimization.Bundle.GetBundleResponse(BundleContext context) +45
System.Web.Optimization.BundleResolver.GetBundleContents(String virtualPath) +166
System.Web.Optimization.AssetManager.EliminateDuplicatesAndResolveUrls(IEnumerable`1 refs) +284
System.Web.Optimization.AssetManager.DeterminePathsToRender(IEnumerable`1 assets) +761
System.Web.Optimization.AssetManager.RenderExplicit(String tagFormat, String[] paths) +35
System.Web.Optimization.Scripts.RenderFormat(String tagFormat, String[] paths) +107
System.Web.Optimization.Scripts.Render(String[] paths) +21
ASP._Page_Views_CodeBase_CodeBaseTbl_cshtml.Execute() in D:\ROOT\GIT\Franjo_dev01\Solution\fCatEve\fCatEve\Views\CodeBase\CodeBaseTbl.cshtml:9
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +198
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9849569
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
Try this, which worked in my system and project:
Open BundleConfig.cs. You should find it at the App_Start folder.
Then change the bundling for your specific script #Scripts.Render("~/scripts/scriptCommon"), from ScriptBundle scriptCommon = new ScriptBundle("~/scripts/scriptCommon"); to Bundle scriptCommon = new Bundle("~/scripts/scriptCommon");
I had a similar problem when upgrading Bootstrap from 4.5 version to 5.*
I set in public static void RegisterBundles(BundleCollection bundles) { ... } method, from:
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));
to:
bundles.Add(new Bundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));
Change ScriptBundle into just Bundle.
I made a web with authentication. When I press the logout button the following error shows, but the logout is correct. I mean, if you reload the page the login form appears and works fine.
Server Error in '/' Application.
Value cannot be null or empty.
Parameter name: contentPath
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.ArgumentException: Value cannot be null or empty.
Parameter name: contentPath
Source Error:
[No relevant source lines]
Source File: c:\Users\User\AppData\Local\Temp\Temporary ASP.NET Files\vs\f60d396e\617997\App_Web_hs3arjh1.3.cs Line: 0
Stack Trace:
[ArgumentException: Value cannot be null or empty.
Parameter name: contentPath]
System.Web.Mvc.UrlHelper.GenerateContentUrl(String contentPath, HttpContextBase httpContext) +130
System.Web.Mvc.UrlHelper.Content(String contentPath) +42
ASP._Page_Views_Shared__Layout_cshtml.Execute() in c:\Users\Manuel\AppData\Local\Temp\Temporary ASP.NET Files\vs\f60d396e\617997\App_Web_hs3arjh1.3.cs:0
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +177
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +80
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +113
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer) +26
System.Web.WebPages.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer) +210
System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +27
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content) +31
System.Web.WebPages.WebPageBase.Write(HelperResult result) +32
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +101
System.Web.WebPages.WebPageBase.PopContext() +146
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +120
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +297
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +248
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +27
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +58
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +349
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +69
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +188
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +124
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +32
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +26
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +24
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +29
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +23
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9742689
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
This is the code to make the logout.
[HttpPost]
public ActionResult Logout()
{
System.Web.Security.FormsAuthentication.SignOut();
Session.Clear();
Session.RemoveAll();
return RedirectToAction("Login", "Login");
}
I tried to make the logout without the session lines but it keeps the session.
Hope you can help me.I encountered that error upon calling a view from my umbraco razor page using RenderMvcController. It's seems it can't render my created macro inside a layout page.
Line 4: }
Line 5:
Line 6: #Umbraco.RenderMacro("ExternalRedirect")
Line 7:
Line 8:
Source File: c:\Working\Git\ID\UMB Packages\Website\Views\Default.cshtml Line: 6
Stack Trace:
[InvalidOperationException: Cannot render a macro when there is no
current PublishedContentRequest.]
Umbraco.Web.UmbracoHelper.RenderMacro(String alias, IDictionary2
parameters) +142 ASP._Page_Views_Default_cshtml.Execute() in
c:\Working\Git\ID\UMB Packages\Website\Views\Default.cshtml:6
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +280
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +125
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage) +196
System.Web.WebPages.WebPageBase.Write(HelperResult result) +89
System.Web.WebPages.WebPageBase.RenderSurrounding(String
partialViewName, Action1 body) +233
System.Web.WebPages.WebPageBase.PopContext() +287
Umbraco.Core.Profiling.ProfilingView.Render(ViewContext viewContext,
TextWriter writer) +140
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
+378 System.Web.Mvc.<>c__DisplayClass1a.b__17()
+33 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func1 continuation)
+799724 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func1 continuation)
+799724 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionResult actionResult) +263
System.Web.Mvc.Async.<>c__DisplayClass25.b__22(IAsyncResult
asyncResult) +787092
System.Web.Mvc.<>c__DisplayClass1d.b__18(IAsyncResult
asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult
ar) +15 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult
asyncResult) +65
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult
ar) +15 System.Web.Mvc.Controller.EndExecute(IAsyncResult
asyncResult) +51
System.Web.Mvc.<>c__DisplayClass8.b__3(IAsyncResult
asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult
ar) +15 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult
asyncResult) +51
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+606 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
public class BlogController : RenderMvcController
{
public BlogController()
: this(UmbracoContext.Current)
{
}
public BlogController(UmbracoContext umbracoContext)
: base(umbracoContext)
{
}
public ActionResult Index(int id)
{
return View("12321");
}
public ActionResult YearPost(int id)
{
string test = "Blog";
var criteria = ExamineManager.Instance.DefaultSearchProvider.CreateSearchCriteria("content");
var filterBlogs = id == 0 ? criteria.NodeTypeAlias("Blog") : criteria.NodeName("Blog");
var result = Umbraco.TypedSearch(filterBlogs.Compile()).ToArray().First();
var renderModel = CreateRenderModel(result);
string viewBlog = "BlogPostPage";
return View(viewBlog, renderModel);
}
private RenderModel CreateRenderModel(IPublishedContent content)
{
var model = new RenderModel(content,CultureInfo.CurrentUICulture);
//add an umbraco data token so the umbraco view engine executes
RouteData.DataTokens["umbraco"] = model;
RouteData.DataTokens["umbraco-doc-request"] = UmbracoContext.PublishedContentRequest;
RouteData.DataTokens["umbraco-context"] = UmbracoContext;
return model;
}
}
I have created a modular MVC project to load other special web project within the same runtime.
Other projects are located in a folder at the root of the website called "Modules".
I am using the attribute PreApplicationStartMethod to load the others assemblies inside the sub directories at boot.
I have added special routes to target each modules with the namespace constraints.
I have create a class who implements RazorViewEngine to override the viewPath when a call is made for the element in the module : ~/Views/Home/Index.cshtml -> ~/Modules/ModuleTest/Views/Home/Index.cshtml.
The Index() method inside the dynamically loaded library is successfully called but i got an error when the view is rendered :
See following image : http://i.imgur.com/KoTgxg2.png
The framework tell me basically that the view has been found but he will not render it.
Do anyone has any idea why the framework refuse to render it ?
Server Error in '/' Application.
The view found at '~/Modules/ModuleTest/Views/Home/Index.cshtml' was not created.
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 view found at '~/Modules/ModuleTest/Views/Home/Index.cshtml' was not created.
Exception
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 view found at '~/Modules/ModuleTest/Views/Home/Index.cshtml' was not created.]
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +362
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
System.Web.Mvc.Async.c__DisplayClass28.b__19() +321
System.Web.Mvc.Async.c__DisplayClass1e.b__1b(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514812
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new TestModel() { Value = "Bla" });
}
}
View
#using Easily.ModuleTest.Models;
#{ ViewBag.Title = "Test Index"; }
#model TestModel
#Model.Value
CustomRazorViewEngine
public class CustomRazorViewEngine : RazorViewEngine
{
public CustomRazorViewEngine()
{
List tmpViewLocationFormats = new List(ViewLocationFormats);
List tmpMasterLocationFormats = new List(MasterLocationFormats);
List tmpPartialViewLocationFormats = new List(PartialViewLocationFormats);
foreach (string moduleDirectory in EasilyModulesContainer.Modules.Select(x => x.Directory))
{
foreach (string viewLocationFormat in ViewLocationFormats)
tmpViewLocationFormats.Add(viewLocationFormat.Replace("~/", string.Format("~/{0}/{1}/", Constants.ModulesDirectory, moduleDirectory)));
foreach (string masterLocationFormat in MasterLocationFormats)
tmpMasterLocationFormats.Add(masterLocationFormat.Replace("~/", string.Format("~/{0}/{1}/", Constants.ModulesDirectory, moduleDirectory)));
foreach (string partialViewLocationFormat in PartialViewLocationFormats)
tmpPartialViewLocationFormats.Add(partialViewLocationFormat.Replace("~/", string.Format("~/{0}/{1}/", Constants.ModulesDirectory, moduleDirectory)));
}
ViewLocationFormats = tmpViewLocationFormats.ToArray();
MasterLocationFormats = tmpMasterLocationFormats.ToArray();
PartialViewLocationFormats = tmpPartialViewLocationFormats.ToArray();
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
return base.CreateView(controllerContext, GetPath(controllerContext, viewPath), masterPath);
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
return base.CreatePartialView(controllerContext, GetPath(controllerContext, partialPath));
}
private string GetPath(ControllerContext controllerContext, string path)
{
if (!controllerContext.RouteData.Values.ContainsKey("_module"))
return path;
Module module = ModulesContainer.Modules.SingleOrDefault(x => x.Name == controllerContext.RouteData.GetRequiredString("_module"));
return path.Replace("~/", string.Format("~/{0}/{1}/", Constants.ModulesDirectory, module.Directory));
}
}
I found the problem by debugging into http://aspnetwebstack.codeplex.com/.
I actually load the library who contain the controllers from another folder than bin in my ModulesContainer class (see question). But inside System.Web.Mvc.dll, one method try to find my controller type by doing a Assembly.Load() in the default directory, its why the BuildManager.GetCompiledType() return null.
I have found a simple way to override this method with :
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
and
private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.RequestingAssembly != null)
return args.RequestingAssembly;
Module module = _modules.SingleOrDefault(x => x.Assembly.FullName == args.Name);
if (module != null)
return module.Assembly;
throw new Exception(string.Format("Unable to load assembly {0}", args.Name));
}
I'm just looking inside my pre-built dll cache to find the already loaded assembly.
#Lex2193: I found problem in your answer.
When I was using your code it was working well except for situation, where referenced assembly has another reference on which it depends:
Module [M] => Dependency [D] => DeepDependency [DD]
When you use in module object from [D] that has in it some calls to something in [DD]. It will fail on TypeLoad exception. Because of requesting assembly.
So i edited code to first searhing for module:
public static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly module = modules.SingleOrDefault(x => x.FullName == args.Name);
if (module != null)
return module;
if (args.RequestingAssembly != null)
return args.RequestingAssembly;
throw new Exception(string.Format("Could not load file or assembly {0}", args.Name));
}
why when i add a param for the constructor of the controller, I get an error.
this is my code:
public partial class RegistrationController : Controller
{
public RegistrationController(int i)
{
}
public ActionResult Index()
{}
}
the error is `Server Error in '/' Application.
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 14:
Line 15: <fieldset>
Line 16: #{string visibleCountry = (Model.CountryParam == ConfigurationParamValue.NotVisible) ? "display:none" : "display:inline";
Line 17: string mandatoryCountry = (Model.CountryParam == ConfigurationParamValue.isMandatory) ? "display:inline" : "display:none";
Line 18: <div id="county" style="#visibleCountry">
Source File: e:\VP5-Nuguet\src\Registration\Registration.Front.Web\Views\Registration\Index.cshtml Line: 16
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Registration_Index_cshtml.Execute() in e:\VP5-Nuguet\src\Registration\Registration.Front.Web\Views\Registration\Index.cshtml:16
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +97
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +260
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +295
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +89
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9630364
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929 `
If you insist the the constructor parameter you have to build your own ControllerFactory implementing the IControllerFactory interface and set it in the app start.
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
MVC will try to instantiate the controller specified in the route for each request by calling its default constructor.
From the looks of it, you want to hit a URL like: /registration/{someNumber}.
If this is the case, move the int id from the constructor to the action method:
public partial class RegistrationController : Controller
{
public RegistrationController()
{ }
public ActionResult Index(int i)
{
// do something
}
}