在asp.net MVC中的POCO Model类中使用HTTPContext变量

时间:2012-03-12 01:25:21

标签: asp.net-mvc poco httpcontext

Controller使用HttpContext请求对象获取相关信息并将其传递给viewmodel。

  

string user = HttpContext.Request.Headers [“abc”]

问题是如何将相同的信息,即HttpContext传递给POCO模型,我必须设置一些参数。我无法使用System.Web.MVC

    public class Test
    {
        public string userA;
        public Test()
        {
            userA = "Here I want to get the user from HttpContext and set it";
        }
     }

使用HTTPContext.Current创建HTTPContextBase对象抛出错误

  

“请求在当前上下文中不可用”

任何帮助都会受到赞赏。谢谢

2 个答案:

答案 0 :(得分:0)

考虑在模型中使用未映射的属性(或设置私有变量的函数)来存储httpcontext中所需的任何信息的值。

您的模型不应该知道httpcontext。模型应与使用它们的环境分开。

另一个想法是,如果您需要使用服务层来执行业务逻辑,其中服务具有由控制器传递给它的上下文信息:

http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs

答案 1 :(得分:0)

虽然最好不要将控制器绑定到HttpContext(如scott.korin提到的那样),但我发现有时无法绕过它(就像测试路由时一样)。

这是我们使用的代码,它基于Steve Sanderson的书“Pro ASP.NET MVC 3 Framework”。密切关注CreateHttpContext方法。

    private void TestRouteMatch(string url, string controller, string action, object routeProperties = null, string httpMethod = "GET")
    {
        // Arrange
        RouteCollection routes = new RouteCollection();
        MvcApplication.RegisterRoutes(routes);
        // Act - process the route
        RouteData result = routes.GetRouteData(CreateHttpContext(url, httpMethod));
        // Assert
        Assert.IsNotNull(result);
        Assert.IsTrue(TestIncomingRouteResult(result, controller, action, routeProperties));
    }

    private bool TestIncomingRouteResult(RouteData routeResult, string controller, string action, object propertySet = null)
    {
        Func<object, object, bool> valCompare = (v1, v2) =>
        {
            return StringComparer.InvariantCultureIgnoreCase.Compare(v1, v2) == 0;
        };
        bool result = valCompare(routeResult.Values["controller"], controller)
        && valCompare(routeResult.Values["action"], action);
        if (propertySet != null)
        {
            PropertyInfo[] propInfo = propertySet.GetType().GetProperties();
            foreach (PropertyInfo pi in propInfo)
            {
                if (!(routeResult.Values.ContainsKey(pi.Name)
                && valCompare(routeResult.Values[pi.Name],
                pi.GetValue(propertySet, null))))
                {
                    result = false;
                    break;
                }
            }
        }
        return result;
    }

    private void TestRouteFail(string url)
    {
        // Arrange
        RouteCollection routes = new RouteCollection();
        MvcApplication.RegisterRoutes(routes);
        // Act - process the route
        RouteData result = routes.GetRouteData(CreateHttpContext(url));
        // Assert
        Assert.IsTrue(result == null || result.Route == null);
    }

    private HttpContextBase CreateHttpContext(string targetUrl = null, string httpMethod = "GET")
    {
        // create the mock request
        Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();
        mockRequest.Setup(m => m.AppRelativeCurrentExecutionFilePath).Returns(targetUrl);
        mockRequest.Setup(m => m.HttpMethod).Returns(httpMethod);
        // create the mock response
        Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();
        mockResponse.Setup(m => m.ApplyAppPathModifier(
        It.IsAny<string>())).Returns<string>(s => s);
        // create the mock context, using the request and response
        Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();
        mockContext.Setup(m => m.Request).Returns(mockRequest.Object);
        mockContext.Setup(m => m.Response).Returns(mockResponse.Object);
        // return the mocked context
        return mockContext.Object;
    }