Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly instantiate HttpContext object?

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).

like image 767
TestK Avatar asked Oct 07 '13 14:10

TestK


1 Answers

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);
like image 168
Mark Cidade Avatar answered Nov 02 '22 19:11

Mark Cidade