我们刚刚开始使用 ASP.Net MVC Release Candidate,我们之前的测试项目是使用 MVC beta 测试 Ajax 请求。
旧代码看起来像这样:
Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();
Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();
Mock<HttpContextBase> context = new Mock<HttpContextBase>();
context.Expect(c => c.Request).Returns(request.Object);
context.Expect(c => c.Response).Returns(response.Object);
request.Expect(req => req["__MVCASYNCPOST"]).Returns("true");
MyController controller = new MyController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
ViewResult result = controller.UpdateStatus() as ViewResult;
然后,对 UpdateStatus 的调用将使用请求对象上的 IsMvcAjaxRequest() 方法来确定要返回给浏览器的内容。
ASP.Net MVC Release Candidate 将 Request.IsMvcAjaxRequest() 更改为 Request.IsAjaxRequest() 的扩展方法意味着我们模拟请求标头的方式更改为:
request.Expect(req => req["X-Requested-With"]).Returns("XMLHttpRequest");
我希望其他人觉得这很有用