简体   繁体   中英

Stack Overflow exception from HostingEnvironment.MapPath

So I have a controller that opens a Json file in my project, as follows:

public class SharedController : Controller
{
        string filePath = HostingEnvironment.MapPath(@"~/App_Data/MenuItems.json");

    // GET: Shared
    [ChildActionOnly]
    public ActionResult _Menu()
    {
        StreamReader sr = new StreamReader(filePath);

        string JsonString = sr.ReadToEnd();
        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All
        };

        var menuItems = JsonConvert.DeserializeObject<List<MenuItem>>(JsonString, settings);


        return View(menuItems.ToList());
    }
}

This code worked when it was part of my home controller and called using Html.Partial.

However now I am doing it from a SharedController, which is called in my layout using Html.Action as follows:

        @Html.Action("_Menu", "Shared")

The error I got is:

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll

Why is this happening and how to I get the filepath without getting an error?

Update: I am pretty sure that HostingEnvironment.MapPath is causing the error because if I try to assign the path a different way I don't get that error, I get a 'folder not found; error on the new StreamReader line.

I think it is recursively calling the _Menu action method, possibly because your partial view you use for the menu is still using the same layout which is again calling the _Men u action method and this cycle never ends until it runs out of memory.

You have 2 options

  1. Call the PartialView() method instead of View() method.

     return PartialView(menuItems.ToList()); 
  2. Make sure your view which renders the menu items is not using the same layout as it's layout. You may explicitly set the layout to null in the _Menu.cshtml view.

     @model List<MenuItem> @{ Layout = null; } <p>Your markup for menu goes here</p> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM