In ASP.Net MVC controller, how do I get a method to recognize data from JSON and Form-urlEncoded formats?

Viewed 74

I'm trying to use ASP.NET code MVC to handle HTTP POST requests as follows:

[Route("coreapi/control")]
public class Control : Controller
{
    [HttpPost(userGroups/{groupId}/users/{userId})]
    public int AddRecord(UserRecord record){
        //This even populates the UserId and GroupId fields in record from the route
    }
}

The above works for Form-UrlEncoded parameters, but not for JSON.

If I want JSON to work, I need to use the [FromBody] attribute like so:

[Route("coreapi/control")]
public class Control : Controller
{
    [HttpPost(userGroups/{groupId}/users/{userId})]
    public int AddRecord([FromBody]UserRecord record, int groupId, int userId){
        //this doesn't look in the route to populate info anymore
        record.GroupId = groupId;
        record.UserId = userId;
    }
}

How do i get both to work in a single method?

1 Answers
Related