[Solved] Object reference not set to an instance of an object Request.Browser set to null NullReferenceException [closed]


This code will not compile as c# will not allow you to have methods and properties that are not defined in a class/type. Really you need to have a class and that class should have a constructor and that constructor should take a Request instance as a parameter and execute a null value check in the constructor. Then make the Request property a private field. This will ensure that:

  1. That a caller will not get some hard to track down NRE at run time.
  2. The code fails early
  3. The requirements of the type are clear as you can’t create a valid instance with a bad state (null value for Request)

Alternatively you could have the method take in a Request instance and have it check if the parameter is not null.

public class EntityNameBusinessLayer
{
    // private member, i left the naming the same but the usual convention for private members is camelcase and not pascal.
    private HttpRequest Request;

    // constructor
    public EntityNameBusinessLayer(HttpRequest request) {
        // check for null
        if(request == null)
            throw new ArgumentNullException("request");
        Request = request; // now the state of the instance is valid and it can be used by the caller
    }

    public string RetrieveUserBrowserDetails()
    { /*your code*/ }
}

Calling code in asp.net web forms

public class YourAspWebPage : System.Web.UI.Page {
    protected void Button_Click(object sender, EventArgs args) {
        var bl = new EntityNameBusinessLayer(this.Request);
        var result = bl.RetrieveUserBrowserDetails();
    }
}

Calling code in an Asp.net Mvc controller. Note that it is discouraged to use the type HttpRequest directly when you are working in Mvc. Instead use the type HttpRequestBase as it is easy to mock/fake for unit testing. See also How do I convert an HttpRequestBase into an HttpRequest object?, the 2nd answer by CountZero (one with the most votes).

public class YourController : System.Web.Mvc.Controller {
    public void SomeAction() {
        var bl = new EntityNameBusinessLayer(System.Web.HttpContext.Current.Request);
        var result = bl.RetrieveUserBrowserDetails();
    }
}

1

solved Object reference not set to an instance of an object Request.Browser set to null NullReferenceException [closed]