关于c#:对象引用未设置为对象的实例Request.Browser设置为null NullReferenceException

Object reference not set to an instance of an object Request.Browser set to null NullReferenceException

有人能告诉我们这段代码有什么问题吗(下面的代码发生在同一个名为EntityNameBusinessLayer的类中,我们使用的是C ASP.NET MVC 5):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using System.Web;
using System.Web.Http;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Globalization;

public HttpRequest Request { get; set; }
public HttpBrowserCapabilities Browser { get; set; }

公共类请求{私有httpRequest请求;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    public Request(HttpRequest request)
    {
        if(request.Browser == null)
        {

        }
        else
        {

        }
    }
}

public HttpBrowserCapabilities Browser { get; set; }

public  class ShogunTypeBusinessLayer
{

public string RetrieveUserBrowserDetails()
{              
    string browserSignature;
    HttpBrowserCapabilities browserCapabilities = Request.Browser;
    string typeBrowser ="Type :" + browserCapabilities.Type +"";
    string nameBrowser ="Name =" + browserCapabilities.Browser +"";
    string versionBrowser ="Version =" + browserCapabilities.Version +"";
    string majorVersionBrowser ="Major Version =" + browserCapabilities.MajorVersion +"";
    string minorVersionBrowser ="Minor Version =" + browserCapabilities.MinorVersion +"";
    string browserCapabilitiesBrowser ="Platform =" + browserCapabilities.Platform +"";
    string betaBrowser ="Is Beta =" + browserCapabilities.Beta +"";
    string isCrawlerBrowser ="Is Crawler =" + browserCapabilities.Crawler + "";
    string isAOLBrowser ="Is AOL =" + browserCapabilities.AOL + "";
    string isWin16Browser ="Is Win16 =" + browserCapabilities.Win16 + "";
    string isWin32Browser ="Is Win32 =" + browserCapabilities.Win32 + "";
    string supportFramesBrowserStatus ="Supports Frames =" + browserCapabilities.Frames +"";
    string supportTableBrowserStatus ="Supports Tables =" + browserCapabilities.Tables +"";
    string supportCookiesBrowserStatus ="Supports Cookies =" + browserCapabilities.Cookies +"";
    string supportVBScriptBrowserStatus ="Supports VB Script =" + browserCapabilities.VBScript +"";
    string supportJavaScriptBrowserStatus ="Supports JavaScript =" + browserCapabilities.JavaScript +"";
    string supportJavaAppletsBrowserStatus ="Supports Java Applets =" + browserCapabilities.JavaApplets +"";
    string supportActiveXControlsBrowserStatus ="Supports ActiveX Controls =" + browserCapabilities.ActiveXControls +"";
    string supportChannelDefinitionFormatBrowserStatus ="CDF =" + browserCapabilities.CDF +"";

    browserSignature = typeBrowser +
                       nameBrowser +
                       versionBrowser +
                       majorVersionBrowser +
                       minorVersionBrowser +
                       browserCapabilitiesBrowser +
                       betaBrowser +
                       isCrawlerBrowser +
                       isAOLBrowser +
                       isWin16Browser +
                       isWin32Browser +
                       supportFramesBrowserStatus +
                       supportTableBrowserStatus +  
                       supportCookiesBrowserStatus +
                       supportVBScriptBrowserStatus +
                       supportJavaScriptBrowserStatus +  
                       supportJavaAppletsBrowserStatus +
                       supportActiveXControlsBrowserStatus +
                       supportChannelDefinitionFormatBrowserStatus;

    return browserSignature;
}

执行之后,我们得到以下异常。我们正试图将附加的字符串保存到数据库中,以便能够确定浏览器已经完成了插入操作。

描述标题:对象引用未设置为对象的实例

描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。

异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。

源错误:

第791行:字符串浏览器签名;第792行:第793行:httpbrowsercapabilities browsercapabilities=request.browser;第794行:第795行:string typebrowser="type:"+browsercapabilities.type+"";

源文件:

1
c:\Users\25025\Documents\Visual Studio 2012\Projects\censys_cross\censys\BusinessLayer\ShogunTypeBusinessLayer.cs    Line:  793

堆栈跟踪:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
[NullReferenceException: Object reference not set to an instance of an object.]
   censys.BusinessLayer.ShogunTypeBusinessLayer.RetrieveUserBrowserDetails() in c:\Users\25025\Documents\Visual Studio 2012\Projects\censys_cross\censys\BusinessLayer\ShogunTypeBusinessLayer.cs:793
   censys.BusinessLayer.ShogunTypeBusinessLayer.AddShogunType(SHOGUN_TYPEda shogunType) in c:\Users\25025\Documents\Visual Studio 2012\Projects\censys_cross\censys\BusinessLayer\ShogunTypeBusinessLayer.cs:1124
   censys.Controllers.ShogunTypeController.Create_Post() in c:\Users\25025\Documents\Visual Studio 2012\Projects\censys_cross\censys\Controllers\ShogunTypeController.cs:33
   lambda_method(Closure , ControllerBase , Object[] ) +101
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651532
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

由于某种原因,代码没有执行。


此代码不会编译为C不允许您拥有未在类/类型中定义的方法和属性。实际上,您需要有一个类,该类应该有一个构造函数,该构造函数应该以一个Request实例作为参数,并在构造函数中执行一个空值检查。然后将请求属性设置为私有字段。这将确保:

  • 在运行时,调用者不会很难找到nre。
  • 代码过早失效
  • 类型的要求很清楚,因为无法创建状态错误的有效实例(请求为空值)
  • 或者,您可以让方法接受一个请求实例,并让它检查参数是否不为空。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    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*/ }
    }

    在ASP.NET Web窗体中调用代码

    1
    2
    3
    4
    5
    6
    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();
        }
    }

    在ASP.NET MVC控制器中调用代码。请注意,当您在MVC中工作时,不鼓励直接使用HttpRequest类型。相反,使用类型HttpRequestBase,因为它很容易为单元测试模拟/伪造。另请参见如何将httpRequestBase转换为httpRequest对象?第二个答案是countzero(票数最多的一个)。

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