简体   繁体   English

启用ASP.NET Web Api以同时容纳JSON和Form编码数据

[英]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. 我在我的MVC应用程序中内置了一个ASP.NET web api,它当前接收了作为表单编码数据的请求所附带的所有数据。

I receive this as a FormDataCollection object and parse like so: 我收到这个作为FormDataCollection对象并解析如下:

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

My response is always a JSON string. 我的回复总是一个JSON字符串。

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. 这很好,我想继续适应这一点,但我希望我的用户能够发送带有内容类型头应用程序/ JSON的JSON 以便我可以支持这两者。

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. asp.net模型绑定器为您处理绑定。 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. 最后,您可以使用jquery ajax或您选择的任何内容发布。 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. 当我说模型课时,我指的是POCO课程。 ASP.NET MVC and Web API should be able to parse the request data in to the class as appropriate. ASP.NET MVC和Web API应该能够根据需要将请求数据解析到类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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