Question

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:

  • HttpPost: results in "Ambiguous reference" (between the Http.HttpPostAttribute and the Mvc.HttpPostAttribute)
  • Json() isn't recognized. It simply gives me a "cannot resolve symbol Json"

If I remember correctly, this would work in a web api project.

What am I doing wrong? Something I need to add?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top