asp.net mvc 中的 Cookie 包装器

Cookie wrapper in asp.net mvc

我正在尝试创建一个 cookie 包装器,以便我可以使用它在我的 mvc 操作中设置和获取 cookie 值。 我们已经有了具有 Request 和 Response 属性的 HttpContextWrapper。

HttpContextWrapper:

 public class HttpContextWrapper : IHttpContext
    {
        private readonly HttpContext _httpContext;
        private readonly HttpContextBase _httpContextBase;

        public HttpContextWrapper(HttpContext httpContext)
        {
            _httpContext = httpContext;
            _httpContextBase = new System.Web.HttpContextWrapper(httpContext);
        }

        public HttpRequest Request
        {
            get { return _httpContext.Request; }
        }

        public HttpContextBase Base
        {
            get { return _httpContextBase; }
        }

        public HttpResponse Response
        {
            get { return _httpContext.Response; }
        }

    }

IHttpContext:

public interface IHttpContext
    {
        HttpRequest Request { get; }
        HttpContextBase Base { get; }
        HttpResponse Response { get; }
    }

1) 我如何重用这个包装器来设置和获取 cookie 值?

2) 扭曲 cookie 值的目的是为了能够执行单元测试。我直接在我的操作方法中设置和获取 cookie 值。相反,我想让它可重用,并可进行单元测试。

非常感谢任何帮助。

谢谢

WH

感谢@DavidTansey 的意见。

实现了以下代码并能够模拟 Response.Cookies。然而,这不是我所期待的上下文包装器,但至少我能够继续前进。

单元测试文件:

public class HttpContextMock:HttpContextBase { 私有 HttpResponseBase 响应;

    public override HttpResponseBase Response
    {
        get
        {
            if (this.response == null)
            {
                this.response = new HttpResponseMock();
            }
            return this.response;
        }
    }
}

public class HttpResponseMock : HttpResponseBase
{
    private HttpCookieCollection cookies;

    public override HttpCookieCollection Cookies
    {
        get
        {
            if (this.cookies == null)
            {
                this.cookies = new HttpCookieCollection();
            }

            return this.cookies;
        }
    }
}

Test.cs:

public void TestMethod()
     {

 var _controller = new HomeContoller();
 var httpContext = new HttpContextMock();
 _controller.ControllerContext = new ControllerContext(httpContext, new RouteData(),_controller);

  var result = _controller.Welcome(userId);

  Assert.AreEqual("Welcome",  _controller.Response.Cookies["TitleMessage"].Value);

}

家庭控制器:

public jsonresult Welcome(int userid)
    {

 ....................

  var cookie = new HttpCookie("TitleMessage") {Value = "Welcome"};
  Response.Cookies.Add(cookie);

}