【问题标题】:mvc3 httpcontext in models模型中的 mvc3 httpcontext
【发布时间】:2012-07-17 22:22:13
【问题描述】:

我目前在我的模型中引用 HttpContext。这是好习惯吗?我应该只传递我需要的信息吗?

例如,在我的模型代码中:

public void function()
{
 string param = HttpContext.Current.Request.QueryString["param"];
 if(param == "myexpectations") { ...}
}

Should be changed to:

public void function(string param) //avoid hard reference this way??
{
 if(param == "myexpectations") { ...}
}

【问题讨论】:

    标签: asp.net-mvc-3 httpcontext


    【解决方案1】:

    在您的模型中引用HttpContext 不是一个好习惯。您不希望模型和HttpContext 之间存在这种紧密耦合。除其他外,这将使您的模型非常难以测试。我肯定会选择你的第二个选项。

    如果您在操作方法中检索查询字符串值,则无需使用HttpContext.Current.Request.QueryString。您可以允许 ASP.NET 的绑定机制将查询字符串值绑定到您的操作方法中的参数。例如。如果这是您的 URI:

    http://localhost/Home/TestQueryString?param=ThisIsATestValue
    

    假设您的路由设置正确,您可以像这样创建控制器和操作,MVC 会将查询字符串值 "ThisIsATestValue" 绑定到参数 param

    public class HomeController : Controller
    {
        public ActionResult TestQueryString(string param)
        {
            string fromHttpContext = HttpContext.Current.Request.QueryString["param"];
    
            // result will be set to true
            bool result = param == fromHttpContext;
            return new EmptyResult();
        }
    }
    

    【讨论】:

    • 您好,您能解释一下并提供 MVC 绑定的链接吗?
    • 当然,这里有一篇很好的解释 MVC 模型绑定的帖子:msdn.microsoft.com/en-us/magazine/hh781022.aspx。我不会在这里解释更多,因为它有很多。我给出的示例是使用 Querystring Value Provider 的一个非常简短的示例(有关更多信息,请参阅链接)。
    • 我很想使用 mvc 框架将 http 参数绑定到模型 (public ActionResult TestQueryString(paramModel params)) 并在控制器中使用它。但是如何在 AuthorizeAttribute 中做到这一点? AuthorizeCore 接受一个参数,那就是 httpContext。我想在 1997 年使用这个对象编写一个 PHP Web 应用程序。然而,展示如何访问参数的示例显示了访问原始 httpcontext。特别是字符串数组会显示为逗号分隔的字符串,但值也有逗号,所以不知道值中的分隔符和逗号是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多