The type or namespace name 'HttpGet' could not be found when add 'System.Web.Http' namespace

Ramesh Rajendran picture Ramesh Rajendran · Oct 11, 2013 · Viewed 37.9k times · Source

I have one issue in MVC .

Currently I am working in MVC and the version is MVC4 . And I have 2 ActionResult Method, see below

[HttpGet]
 public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

 [HttpPost]
 public ActionResult About(ModelName ccc)
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

We need the using System.Web.Mvc; namespace for [HttpPost] and [HttpGet] attributes. So I added the using System.Web.Mvc; namespace in my controller . But i need to add another one Namespace using System.Web.Http; for httpsresponseexpection error handling in my controller .Si I added in the namespace . At this time System.Web.Mvc; is not working .

I got this error: The type or namespace name 'HttpGet' could not be found . Why ? anything relation between System.Web.Mvc and System.Web.Http for HttpGet ?

Answer

Darin Dimitrov picture Darin Dimitrov · Oct 11, 2013

The reason you are getting this exception is because there are 2 different HttpGetAttribute classes in 2 different namespaces:

The first is used in ASP.NET MVC controllers and the second is used in ASP.NET Web API controllers.

When you imported the second namespace the compiler is no longer able to disambiguate which of the 2 classes you are referring to because the 2 namespaces are in scope.

Basically Microsoft duplicated all the classes that existed in ASP.NET MVC for the Web API but placed them in different namespace. Basically you shouldn't be mixing those namespaces.

But i need to add another one Namespace using System.Web.Http; for httpsresponseexpection error handling in my controller

Why would you need to use this in an ASP.NET MVC controller? Normally that's something you should be doing in a Web API controller.

But if for some reason you need to mix the 2 you will have to explicitly specify which attribute you need to use by fully qualifying it:

[System.Web.Mvc.HttpGet]
public ActionResult About()
{
    ViewBag.Message = "Your app description page.";
    return View();
}