40

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.

Dr1Ku
  • 2,690
  • 3
  • 43
  • 52
Mohayemin
  • 3,761
  • 4
  • 23
  • 51

2 Answers2

48

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.

Dr1Ku
  • 2,690
  • 3
  • 43
  • 52
karaxuna
  • 25,822
  • 11
  • 76
  • 111
  • 4
    Good shout, I think sometimes resharper can be a dangerous thing but without it I perhaps wouldn't have read this. Cheers guys. P.S hugs and kisses for resharper :) – Adam Aug 29 '13 at 19:36
15

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.

Arjan
  • 825
  • 9
  • 12
  • 3
    System.Web.HttpContext.Current.Request :) – lsp Jul 10 '14 at 10:01
  • 2
    FYI: Request.Url is not null if your base controller inherits from Controller, i.e. BaseController : Controller – Carl Winder Jun 03 '15 at 14:28
  • 1
    Just be aware that using `System.Web.HttpContext` can interfere with testing that needs to mock the `HttpContext` (since there's no actual IIS request occurring during unit testing). See [HttpContextBase vs. HttpContext](http://www.splinter.com.au/httpcontext-vs-httpcontextbase-vs-httpcontext/) and [How to get HttpContextBase object from HttpContext.Current](http://thecodersperspective.blogspot.com/2011/07/how-to-get-httpcontextbase-object-from.html) – ErikE Mar 01 '16 at 18:49