fbpx

Our Black Friday Sale has been extended!  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)
{
  base.Initialize(requestContext);
  // now Server has been initialized
  folderPath = Server.MapPath("~/uploads");
}

About the Author:

Visionfriendly.com

Visionfriendly.com

VisionFriendly.com is a Chicago digital marketing agency with over 25 years of experience helping clients nationwide. We have an in-house team of marketers and creatives ready to improve your business’s marketing operations.

Share On:

Comments:

Leave a Comment

Your email address will not be published. Required fields are marked *

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

We’re Doing Something Awesome

VisionFriendly.com is now Blackbird Digital.

We are the same great people, with a new name, new website, and new ideas.

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