简体   繁体   中英

Enabling ASP.NET Web Api to accommodate both JSON and Form encoded data

I have an ASP.NET web api built into my MVC application and it currently receives all data accompanying a request as form encoded data.

I receive this as a FormDataCollection object and parse like so:

public string Post(FormDataCollection data)
{
    var first = data.Get("FirstName");
    //for every supported field.
}

My response is always a JSON string.

This is fine and I want to continue to accomodate this, however I'd like my users to be able to send a JSON with content type header application/JSON as well so that I can support both.

How do I accommodate both in a simple way? Will it have to involve checking the content header and having different code to extract the attributes in each case?

Let the asp.net model binder handle the bindings for you. Define a class that will represent your model:

public class Person
{
  public string Firsname{ get; set; }
}

then have your controller action take this view model as argument:

public class PersonController : ApiController
{

  public void Post(Person model)
  {
    ...
  }
}

Finally you can post using jquery ajax or whatever you pick. eg

$.ajax({
type: 'POST',
url: '/api/person',
cache: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Firstname: "John Doe" }),
success: function() {
    ...    
   }
});

Try using a model class like below;

public class MyTargetModel
{
    public string FirstName { get; set; }
}

public string Post(MyTargetModel model)
{
    var first = model.FirstName;
    //for every supported field.
}

When I say model class I mean a POCO class. ASP.NET MVC and Web API should be able to parse the request data in to the class as appropriate.

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