c# - 如何将 HttpRequest 接收到 MVC 3 Controller 操作中?

标签 c# asp.net asp.net-mvc-3 unit-testing c#-4.0

当前解决方案

所以我有一些非常相似的东西

[HttpPost]
    public ActionResult Upload()
    {
        var length = Request.ContentLength;
        var bytes = new byte[length];

        if (Request.Files != null )
        {
            if (Request.Files.Count > 0)
            {
                var successJson1 = new {success = true};
                return Json(successJson1, "text/html");
            }
        }
...
        return Json(successJson2,"text/html");
    }

单元可测试解决方案?

我想要这样的东西:

[HttpPost]
public ActionResult Upload(HttpRequestBase request)
{
    var length = request.ContentLength;
    var bytes = new byte[length];

    if (request.Files != null )
    {
        if (request.Files.Count > 0)
        {
            var successJson1 = new {success = true};
            return Json(successJson1);
        }
    }

    return Json(failJson1);
}

但是这失败了,这很烦人,因为我可以从基类创建一个 Mock 并使用它。

注意事项

  • 我知道这不是解析表单/上传的好方法,并且会 想说这里发生了其他事情(即这个上传 可以是表单或 xmlhttprequest - 操作不知道是哪个)。
  • 使“请求”单元可测试的其他方法也很棒。

最佳答案

您已经有一个 Request Controller 上的属性 => 您不需要将其作为操作参数传递。

[HttpPost]
public ActionResult Upload()
{
    var length = Request.ContentLength;
    var bytes = new byte[length];

    if (Request.Files != null)
    {
        if (Request.Files.Count > 0)
        {
            var successJson1 = new { success = true };
            return Json(successJson1);
        }
    }

    return Json(failJson1);
}

现在您可以在单元测试中模拟 Request,更具体地说,模拟具有 Request 属性的 HttpContext:

// arrange
var sut = new SomeController();
HttpContextBase httpContextMock = ... mock the HttpContext and more specifically the Request property which is used in the controller action
ControllerContext controllerContext = new ControllerContext(httpContextMock, new RouteData(), sut);
sut.ControllerContext = controllerContext;

// act
var actual = sut.Upload();

// assert
... assert that actual is JsonResult and that it contains the expected Data

关于c# - 如何将 HttpRequest 接收到 MVC 3 Controller 操作中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10737134/

相关文章:

c# - 如何从 ContentPage 获取应用版本?

c# - System.Type 到 XmlSchema 内置类型

c# - C#通过发布请求发送Cookie

javascript - 将文本发送到数组中的特定 li

asp.net - window.location 更改失败 AJAX 调用

c# - 如何获取模型属性的 id 以便与 MVC3 中的自定义 IClientValidatable 一起使用

c# custom group by 对于大型数据集真的很慢

asp.net - 从表单例份验证中排除页面 - ASP.NET

asp.net-mvc - 没有 [required] 属性的 Razor 验证触发

c# - 如何使用 asp.net mvc 和单元测试组织代码和测试