如何在ASP.NET MVC中测试ajax submition?

时间:2022-12-04 18:31:41

Specifically, how can I pass the static method Request.IsAjaxRequest()?

具体来说,我如何传递静态方法Request.IsAjaxRequest()?

I get the exception 'System.ArgumentNullException' when I try to test the following code:

当我尝试测试以下代码时,我得到异常'System.ArgumentNullException':

if (Request.IsAjaxRequest())
{
  return Json(data);
}
return View(data2);

I'm using Moq. Thanks for any help.

我正在使用Moq。谢谢你的帮助。

1 个解决方案

#1


You need mocking Request and Request.Headers to work with Request.IsAjaxRequest():

您需要模拟Request和Request.Headers来处理Request.IsAjaxRequest():

var request = new Mock<HttpRequestBase>();
request.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection {
    {"X-Requested-With", "XMLHttpRequest"}
});

var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);

var controller = new YourController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);

#1


You need mocking Request and Request.Headers to work with Request.IsAjaxRequest():

您需要模拟Request和Request.Headers来处理Request.IsAjaxRequest():

var request = new Mock<HttpRequestBase>();
request.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection {
    {"X-Requested-With", "XMLHttpRequest"}
});

var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);

var controller = new YourController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);