7

I am trying to create a simple code to retrieve a string for the current url as follows:

string currentURL = HttpContext.Current.Request.Url.ToString();

However, I get the error upon running the code: Object reference not set to an instance of an object.

I assume I have to create an instance of HttpContext. The arguments for HttpContext are either HttpContext(HttpRequest request, HttpResponse response) or HttpContext(HttpWorkerRequest wr).

Is there documentation that details how to work with these arguments? I'm fairly new to C#, so I'm not entirely sure how to instantiate this object properly, and have not found any resources that have been helpful (including MS library).

John Saunders
  • 160,644
  • 26
  • 247
  • 397
TestK
  • 323
  • 1
  • 4
  • 14
  • 4
    Why do you have to *create an instance* of `HttpContext`? **Where is this code located?** You don't want to create it on your own, it's created when routing occurs. – Mike Perrenoud Oct 07 '13 at 14:30
  • Sounds like you are making a utility class. In that case work with HttpContext within your codebehind and do anything utility-like in the utility class. I've had this issue before. – RealityDysfunction Oct 07 '13 at 14:33
  • The fact that you're getting an `ObjectReference` exception doesn't mean that the `Current` context is `null`. You have two other chained properties that could throw that error. Are you certain it's the `Current` context property? – Mike Perrenoud Oct 07 '13 at 14:40
  • Hi @neoistheone, to be honest I am not sure that it's the `Current` context property, I was assuming that was where the exception was occurring. After inputting Mark's solution, I continue to get the `ObjectReference` exception, so I am not sure where the issue lies within the `HttpContext` line. – TestK Oct 07 '13 at 14:44
  • 2
    @TestK, well I would say throw a breakpoint on that line and figure out **which property** is `null`. That will be step 1. – Mike Perrenoud Oct 07 '13 at 14:46
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Oct 13 '13 at 02:44

1 Answers1

12

The HttpContext object is instantiated, once per request thread, by the ASP.NET infrastructure. You have to be running ASP.NET on a web server (e.g., IIS) for it to be available. It is not meant to be initialized in user code. You are already accessing that instance through the HttpContext.Current static property. It will be null if you are not running ASP.NET.

If you really wanted to, though, you could instantiate one based on the request and response of an existing HttpContext:

var request    = HttpContext.Current.Request;
var response   = HttpContext.Current.Response;
var newContext = new HttpContext(request, response);
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236