Our Black Friday Sale is here!  View Sale

MVC: The Server object is null in the controller’s constructor

Overlapping colored triangles

If you are trying to initialize some data in your controller's constructor, you may run into an issue in which the Server object is null. For example, the following code will throw the error:

    Object reference not set to an instance of an object
public class MyController : Controller
  private string folderPath;
  public MyController()
    // Throws an error because Server is null
    folderPath = Server.MapPath("~/uploads");
    // Throws an error because this.ControllerContext is null
    folderPath = this.ControllerContext.HttpContext.Server.MapPath("~/uploads");

The correct place for this code is in the Initialize() method of the controller:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
  // now Server has been initialized
  folderPath = Server.MapPath("~/uploads");

About the Author:



VisionFriendly.com has been building successful websites for over 20 years and covers all areas of website design, development and marketing with creative custom web designs and a robust in-house team of programmers to get your web marketing to work exactly the way you need it to.

Share On:


Leave a Comment

Your email address will not be published.

Copyright © 2022, All Rights Reserved
Tri Colored Triangles
Scroll to Top

Take your business to the

Next Level!

Visionfriendly.com has the right team to make your business stand out from other professional websites.

Ready For Takeoff?

A Completely Customized
Digital Marketing Experience

  • We'll be in touch within one business day to discuss your goals and create a personalized plan that fits both you and your business.

  • This field is for validation purposes and should be left unchanged.

Let’s start a Conversation