创建新列表时,对象引用未设置为对象的实例

时间:2017-06-12 11:37:01

标签: c# asp.net .net model-view-controller

今天我在ASP.NET MVC应用程序的Request控制器中遇到了Signals(int?id)方法的问题。代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebInterface.DAL;
using WebInterface.Exceptions;
using WebInterface.Interfaces;
using WebInterface.Models;

namespace WebInterface.Controllers
{
    public class RequestController : Controller
    {
        private readonly Converter _converter = new Converter();
        private readonly BeheerContext _beheerContext = new BeheerContext();
        // GET: Request
        public ActionResult Add(string category, string name, string ip, string a, string b, string c, string d, string e, string f, string g, string h, string i, string j)
        {
            string[] receivedSignalStrings = {a, b, c, d, e, f, g, h, i, j};
            var signals = _converter.ConvertSignalStringsToSignals(receivedSignalStrings);
            var request = new Request(category, name, ip, signals);
            if (request.RequestHasReportName(request.Name) && request.RequestIsBle(request.Category))
            {
                request.AddToDb(request);
            }
            //wrong signal

            return View(request);
        }

        public ActionResult Index()
        {
            var requests = _beheerContext.Requests;
            return View(requests);
        }

        public ActionResult Signals(int id)
        {
            try
            {
                if (id == 0)
                {
                    throw new HttpException(404, "Not Found");
                }
                if (_beheerContext.Requests == null)
                {
                    throw new CustomException("Geen verbinding met de database.");
                }

                var request = _beheerContext.Requests.FirstOrDefault(r => r.Id == id);
                if (request == null)
                {
                    throw new CustomException("Signaal niet gevonden in database.");
                }
                List<Signal> signalList = new List<Signal>();

                foreach (var requestSignal in request.Signals)
                {
                    signalList.Add(_beheerContext.Signals.FirstOrDefault(s => s.Id == requestSignal.Id));
                }
                return View(signalList);
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }
    }
}

当使用正确的参数id执行此方法时,它会在命中我创建signalList的行时抛出NullReferenceException。这一行:

List<Signal> signalList = new List<Signal>();

异常的堆栈跟踪显示了这个确切的行,在调试时它将转到我的Global.asax.cs中的Application_error方法,它将检测Server.GetLastError(),如下所示:

void Application_Error(object sender, EventArgs e)
    {
        var exception = Server.GetLastError();
        Response.Clear();

Exception

我一直在谷歌搜索这个问题,但我找不到任何类似的问题。

编辑:这个问题与任何其他NullReferenceException问题都不相似,因为我在执行代码之前检查了所有null。除了NullReferenceException被抛出一行,我将一个新列表分配给一个本地变量,该变量不会引用任何可能为null的变量。

信号类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebInterface.DAL;
using WebInterface.Interfaces;

namespace WebInterface.Models
{
    public class Signal
    {
        public int Id { get; set; }
        public string SourceMacAddress { get; set; }
        public int RSSI { get; set; }
        public int Time { get; set; }

        public Signal(string macAddress, int rsi, int time)
        {
            SourceMacAddress = macAddress;
            RSSI = rsi;
            Time = time;
        }

        public Signal()
        {

        }

        public void AddToDb(Signal signal)
        {
             IBeheerContext db = new BeheerContext();
            var signals = db.Signals;
            signals.Add(signal);
            db.SaveChanges();
        }
   }
}

异常的Stacktrace:

at WebInterface.Controllers.RequestController.Signals(Nullable`1 id) in C:\Users\Jvandekraats\Source\Workspaces\Projects\WebInterface\WebInterface\Controllers\RequestController.cs:line 54
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)

0 个答案:

没有答案