对象引用未设置为对象的实例Request.Browser设置为null NullReferenceException

时间:2016-08-18 20:26:01

标签: c# asp.net asp.net-mvc-4 asynchronous

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

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请求;

    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行:string browserSignature; 792行: 第793行:HttpBrowserCapabilities browserCapabilities = Request.Browser; 794行: 第795行:string typeBrowser ="输入:" + browserCapabilities.Type +" &#34 ;;

源文件:

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

堆栈追踪:

[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

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

1 个答案:

答案 0 :(得分:1)

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

  1. 调用者在运行时不会很难找到NRE。
  2. 代码提前失败
  3. 类型的要求很明确,因为您无法创建状态为错误的有效实例(请求为空值)
  4. 或者,您可以让方法接受Request实例,并检查参数是否为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*/ }
    }
    

    在asp.net网络表单中调用代码

    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,因为它很容易模拟/伪造单元测试。另请参阅How do I convert an HttpRequestBase into an HttpRequest object?,CountZero的第二个答案(投票率最高的)。

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