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

无人久伴 提交于 2019-12-02 22:19:00

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();
}

For the record, I had a similar issue in a class library with a reference to MVC. I installed a nuget package in the class library that itself had a dependency on MVC (note: the new package was: RazorGenerator.Mvc). Previously, the class library relied on a Sytem.Web.Mvc.dll reference added using the 'Add Reference' dialogue rather than on one installed via the "Microsoft.AspNet.Mvc" nuget package.

Nuget chose the lowest MVC version that would meet the dependency requirements of the new package. That meant that the previous reference (to MVC 5) was replaced with a lower version reference (to MVC 3).

Upgrading the MVC version in the class library using nuget resolved the issue.

Here is solution for that problem try it....

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

        return View();
    }

I ran into this problem on OS X using .NET Core. I was missing an entry for Microsoft.AspNetCore.Mvc in my project.json.

Before:

{
    "dependencies": {
        "Microsoft.NETCore.App": {
          "version": "1.0.0",
          "type": "platform"
        },
        ...,
        "Microsoft.Extensions.Configuration.CommandLine": "1.0.0"
      },
...
}

After:

{
    "dependencies": {
        "Microsoft.NETCore.App": {
          "version": "1.0.0",
          "type": "platform"
        },
        ...,
        "Microsoft.AspNetCore.Mvc": "1.0.0",
        "Microsoft.Extensions.Configuration.CommandLine": "1.0.0"
      },
...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!