Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can Request.Url be null?

In my controller code I am using: Request.Url.<Something>. ReSharper suggests that Request.Url can be null.

So, when exactly can Request.Url be null? I am not talking about testing, I am interested only about an Application that is live / has already been deployed.

Please note that I have not received any NullReferenceExceptions from using Request.Url up to this point.

like image 825
Mohayemin Avatar asked Aug 27 '12 06:08

Mohayemin


2 Answers

HttpRequestBase is a class and ReSharper sees it as an actual Class, nothing more (theoretically, it can be null). So it does not analyze the usage of this specific Class.

In reality, I think that Request.Url will never be null, so just ignore ReSharper in this case.

like image 93
karaxuna Avatar answered Oct 19 '22 22:10

karaxuna


Actually a NullReferenceException can occur when using Request.Url. When you create your own base controller class from which other classes derive, Request will be null. Or when using ActionMailer with ASP.NET MVC you'll have to create a controller class that derives from MailerBase (which also causes Request inside this controller to be null).

Alternative: use HttpContext.Current.Request or check whether Request is null.

like image 33
Arjan Avatar answered Oct 19 '22 22:10

Arjan