简体   繁体   中英

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

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?

So, this seems really silly, but from experimentation and reading this very informative article , it looks like the only way to do this is with two separate methods.

One for form-urlencoded data

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

and one for json:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM