添加’System.Web.Http’命名空间时,找不到类型或命名空间名称’HttpGet’
我在MVC中有一个问题。
目前我在MVC工作,版本是MVC4。 我有2个ActionResult方法,见下文
[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(); }
我们需要using System.Web.Mvc;
[HttpPost]和[HttpGet]属性的命名空间。 所以我添加了using System.Web.Mvc;
控制器中的命名空间。 但我需要using System.Web.Http;
添加另一个命名空间using System.Web.Http;
对于我的控制器中的httpsresponseexpectionerror handling。我在命名空间中添加了。 这时System.Web.Mvc;
不管用 。
我收到此错误: 无法找到类型或命名空间名称’HttpGet’ 。 为什么? HttpGet的System.Web.Mvc和System.Web.Http之间的任何关系?
获得此exception的原因是因为在2个不同的命名空间中有2个不同的HttpGetAttribute
类:
-
System.Web.Mvc.HttpGetAttribute
-
System.Web.Http.HttpGetAttribute
第一个用于ASP.NET MVC控制器,第二个用于ASP.NET Web API控制器。
导入第二个命名空间时,编译器不再能够消除您引用的2个类中的哪个类的歧义,因为2个命名空间在范围内。
基本上,Microsoft复制了ASP.NET MVC中存在的所有用于Web API的类,但是将它们放在不同的命名空间中。 基本上你不应该混合这些命名空间。
但我需要使用System.Web.Http添加另一个命名空间; 用于我的控制器中的httpsresponseexpectionerror handling
为什么需要在ASP.NET MVC控制器中使用它? 通常,您应该在Web API控制器中执行此操作。
但是如果由于某种原因你需要混合2,你必须通过完全限定它来明确指定你需要使用哪个属性:
[System.Web.Mvc.HttpGet] public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); }
为了记录,我在类库中有一个类似的问题,引用了MVC。 我在类库中安装了一个nuget包,它本身依赖于MVC(注意:新包是:RazorGenerator.Mvc)。 以前,类库依赖于使用“添加引用”对话框添加的Sytem.Web.Mvc.dll引用,而不是通过“Microsoft.AspNet.Mvc”nuget包安装的引用。
Nuget选择了最低的MVC版本,以满足新软件包的依赖性要求。 这意味着先前的引用(对于MVC 5)被替换为较低版本引用(对于MVC 3)。
使用nuget升级类库中的MVC版本解决了这个问题。
这是问题的解决方案试试吧….
[System.Web.Mvc.HttpGet] public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); }
我使用.NET Core在OS X上遇到了这个问题。 我在project.json
缺少Microsoft.AspNetCore.Mvc
的条目。
之前:
{ "dependencies": { "Microsoft.NETCore.App": { "version": "1.0.0", "type": "platform" }, ..., "Microsoft.Extensions.Configuration.CommandLine": "1.0.0" }, ... }
后:
{ "dependencies": { "Microsoft.NETCore.App": { "version": "1.0.0", "type": "platform" }, ..., "Microsoft.AspNetCore.Mvc": "1.0.0", "Microsoft.Extensions.Configuration.CommandLine": "1.0.0" }, ... }