尝试读取或写入受保护的内存

Int*_*tor 1 nunit rhino mvccontrib-testhelper c#-4.0 asp.net-mvc-3

我有一个示例ASP.NET MVC 3 Web应用程序,遵循Jonathan McCracken的Test-Drive Asp.NET MVC(顺便说一句好书),我偶然发现了一个问题.请注意,我使用的是MVCContrib,Rhino和NUnit.

    [Test]
    public void ShouldSetLoggedInUserToViewBag() {
        var todoController = new TodoController();
        var builder = new TestControllerBuilder();
        builder.InitializeController(todoController);

        builder.HttpContext.User = new GenericPrincipal(new GenericIdentity("John Doe"), null);

        Assert.That(todoController.Index().AssertViewRendered().ViewData["UserName"], Is.EqualTo("John Doe"));
    }
Run Code Online (Sandbox Code Playgroud)

上面的代码总是抛出这个错误:

System.AccessViolationException:尝试读取或写入受保护的内存.这通常表明其他内存已损坏.

控制器操作代码如下:

[HttpGet]
    public ActionResult Index() {
        ViewData.Model = Todo.ThingsToBeDone;
        ViewBag.UserName = HttpContext.User.Identity.Name;

        return View();
    }
Run Code Online (Sandbox Code Playgroud)

根据我的想法,应用程序似乎崩溃,因为控制器操作中的两个分配.但是,我看不出有多么错误!?

任何人都可以帮我找出解决这个问题的方法.

谢谢.

编辑1

我做了一些实验来看看问题是什么.删除ViewData,Model分配时,问题会超越Expected result to be of type ViewResult. It is actually of type ViewResult..该ViewData分配是如此基本,我不认为是这样,我认为这个问题有什么问题或者犀牛或MVCcontrib结合MVC 3.

我之前为同一控制器操作编写了以下测试:

        [Test]
    public void ShouldDisplayAListOfTodoItems() {
        Assert.That(((ViewResult)new TodoController().Index()).ViewData.Model, Is.EqualTo(Todo.ThingsToBeDone));
    }
Run Code Online (Sandbox Code Playgroud)

这个现在失败了,System.NullReferenceException : Object reference not set to an instance of an object可能因为没有为这个特定的测试设置HttpContext.删除ViewBag作业时,一切正常.

希望能使问题更加清晰.

编辑2

在删除ViewData.Model赋值后调试代码时,它会抛出一个不同的错误:System.NullReferenceException : Object reference not set to an instance of an object.ViewBag赋值时.

Int*_*tor 5

好吧,我把这个打倒了.正如我所怀疑的那样,这是因为MVCContrib.请注意,我使用的MVC 3 Beta尚未得到MVCContrib的正式支持.考虑到这一点,我已经下载了MVC 3分支的最新MVCContrib源代码.

转到MVCContrib Sources,切换到mvc3分支,下载并使用附加的bat构建二进制文件.然后,将所需文件包含在您的解决方案中.

好吧,这可能会在未来的稳定版本中修复,但我想这可能对其他人有用.感谢Darin的兴趣.