MVC项目内的Apicontroller - 没有识别HttpPost和JSON方法
-
24-12-2019 - |
题
我有一个普通的ASP.NET MVC项目(不是Web API)。在这里,我在我的控制器内创建了一个名为“API”的新文件夹,因为我想创建一个简单的API。
然后我创建以下类:
public class OfficeProductController : ApiController
{
[HttpPost]
public JsonResult Create(OfficeProductViewModel model)
{
var obj = new OfficeProductViewModel();
return Json(obj);
}
}
.
这里我得到两个问题:
- httppost:导致“模糊参考”(在http.httppostattribute和mvc.httppostattribute之间)
- json()没有识别。它只是给了我一个“无法解析象征json”
如果我记得正确,这将在Web API项目中工作。
我做错了什么?我需要添加的东西?
解决方案
lars,第二个问题=>您可以返回OfficeProductViewModel而不是JsonResult。 jsonresult是一个在webapi中使用的actureResult。
jsonresult在system.web.mvc命名空间中,其中apicontroller在system.web.http(web api sift)中。
first问题=>确保在Apicontroller中没有引用System.Web.mvc,只需system.web.http。两个名称空间中有一个httppost对象,您不想使用MVC版本。
要将JSON设置为Apicontrollers上的默认返回类型而不是XML,您可以像这样的方式覆盖它的WebAPIConfig类;
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
.
scott hanselman也有一个很好的文章; http://www.hanselman.com/blog/oneaspnetmakesjsonwebapiswithaspnetmakingjsonwebapiswithaspnetmakni.aspx
不隶属于 StackOverflow