asp.net mvc中的Cookie包装器

时间:2015-03-17 18:41:13

标签: asp.net-mvc-3 cookies wrapper dry httpcontext

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

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

1 个答案:

答案 0 :(得分:0)

感谢@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);

}

HomeController中:

public jsonresult Welcome(int userid)
    {

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

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

}