سؤال

My controller has usings declared like this (not sure if order matters)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

I am trying to access HTTPContext and noticed that I can't even get HTTPContext.Current

It seems that there are two HTTPContext variables and the MVC one was taking precedent. I had to fully qualify the object's namespace in order to get the app to compile.

  • Why are there two HTTPContext variables?
  • Does the order of the usings affects which object my conflicted object will compile with?
هل كانت مفيدة؟

المحلول

System.Web.HttpContext is a type which has a static Current property that you're using to get the current context.

There isn't a System.Web.Mvc.HttpContext type. What you're probably seeing is the HttpContext property exposed by the Controller type. This property gives you the context the controller is currently executing in and acts as a way to get the "current" context. It's considered superior, because you can inject a fake context for the purposes of testing your controllers, whereas it's very hard to fake HttpContext.Current.

Although not entirely relevant, the order of usings doesn't matter: they're all checked and if two possible types are found the compiler will throw an exception about the ambiguity. What does matter is whether you declare your usings inside or outside of the namespace declaration. The compiler checks the "inner" context first, so that if you declare types in your namespace, the types in the using statements inside the namespace are checked first and will take precedence over your own types. If you move the using statements outside of the namespace, the types in your namespace will take precedence.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top