Reputation: 9966
I have a normal ASP.NET MVC project (not Web API). Here I created a new folder inside my controllers called "api", as I want to create a simple api.
I then create the following class:
public class OfficeProductController : ApiController
{
[HttpPost]
public JsonResult Create(OfficeProductViewModel model)
{
var obj = new OfficeProductViewModel();
return Json(obj);
}
}
Here I get two problems:
If I remember correctly, this would work in a web api project.
What am I doing wrong? Something I need to add?
Upvotes: 3
Views: 1962
Reputation: 947
Lars, Second question => you can just return OfficeProductViewModel instead of JsonResult. JsonResult is an ActionResult, not used in WebApi.
JsonResult is in the System.Web.MVC namespace where ApiController is in the System.Web.Http (Web Api stuff).
First question => Make sure you are not referencing System.Web.MVC in your APIController, just System.Web.Http. There is an HttpPost object in both namespaces, you do not want to use the MVC version.
To set Json as the default return type on ApiControllers instead of xml you can override this in you WebApiConfig class like so;
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
Scott Hanselman has a nice article on this as well; http://www.hanselman.com/blog/OneASPNETMakingJSONWebAPIsWithASPNETMVC4BetaAndASPNETWebAPI.aspx
Upvotes: 6