0

I currently reference HttpContext in my models. Is this good practice? Should I just pass in information I need instead?

For example, in my model code:

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") { ...}
}
River
  • 1,487
  • 3
  • 15
  • 25

1 Answers1

1

It is not good practice to reference HttpContext in your models. You don't want that kind of tight coupling between your model and HttpContext. It will make your model very difficult to test, among other things. I would definitely go with your second option.

If you are retrieving your query string values in an action method, you don't need to use HttpContext.Current.Request.QueryString. You can allow ASP.NET's binding mechanism to bind the query string values to parameters in your action method. E.g. If this is your URI:

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

Assuming you have your routes set up correctly, you can create your controller and action like this and MVC will bind the query string value "ThisIsATestValue" to the paramater 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();
    }
}
Kevin Aenmey
  • 13,259
  • 5
  • 46
  • 45
  • Hi, can you please explain and provide a link to MVC bind? – River Jul 18 '12 at 23:53
  • Sure, here is a great post explaining MVC model binding: http://msdn.microsoft.com/en-us/magazine/hh781022.aspx. I won't explain more here since there is a lot to it. The example I gave is a very brief example of using the Querystring Value Provider (see the link for more info). – Kevin Aenmey Jul 19 '12 at 01:29
  • I would love to use the mvc framework binding http parameters to models (`public ActionResult TestQueryString(paramModel params)`) and use it in the controllers. But how to do this in a AuthorizeAttribute? The AuthorizeCore takes one argument and that is httpContext. I feel like programming a PHP web app in 1997 using this object. Yet examples showing how to access parameters show accessing raw httpcontext. Especially an array of strings would show up as a comma seperated string but the values also have comma's so no idea what is the seperator and the comma in the value anymore. – HMR Jul 07 '16 at 05:35