在Web API 2操作中接收JSON格式的数据? [英] Receiving JSON-formatted data in a Web API 2 action?

查看:338
本文介绍了在Web API 2操作中接收JSON格式的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON作为输入和输出的RESTful API,传入的请求应具有包含相关数据的JSON格式的主体,并且响应将类似地以JSON格式.

I'm working on a RESTful API using JSON for the input and output - requests coming in should have JSON formatted bodies containing relevant data and the response will similarly be JSON formatted.

我遇到的问题是我一生无法解决如何从POST请求中收集信息并将其正确映射到相关对象的问题.

The problem I'm having is that I can't for the life of me figure out how to collect the information from the POST request and have it properly mapped to the relevant objects.

例如,我想允许对"/contacts"的POST请求,该请求将包含类似于以下内容的JSON格式的Contact对象:

For example, I want to allow POST requests for "/contacts" which will contain a JSON formatted Contact object similar to this:

{"Given":"John", "Surname":"Doe"}

问题是,无论我如何尝试,我都无法采取接收动作来识别此信息.如何在操作中访问在请求正文中提交的JSON对象?

The problem is, no matter what I try I can't get the receiving action to recognise this information. How do I access the JSON object submitted in the request body, within my action?

[RoutePrefix("contacts")]
public class ContactsController : BaseController
{
    [Route("")]
    [ResponseType(typeof(ApiResponse))]
    public IHttpActionResult PostContacts(FormDataCollection data)
    {
        ApiResponse response = new ApiResponse();

        response.Data = data;

        return Ok(response);
    }
}

响应始终包含"response.Data"的空值,当我调试应用程序时,我可以看到"data"实际上为空.

The response always contains a null value for "response.Data" and when I debug the application I can see that "data" is in fact null.

我忘了提起我喜欢的方式了.理想情况下,我希望我的动作具有类似于以下内容的签名:

I forgot to mention how I'd like this to work. Ideally I want my action to have a signature similar to this:

public IHttpActionResult PostContacts(Contact contact) {}

根据传入请求正文中包含的JSON自动填充contact变量的地方.

Where the contact variable is populated automatically based off the JSON included in the incoming request body.

推荐答案

如果您的Contact类的属性名称与JSON对象中的属性名称相同,则

If your Contact class has same property names as in JSON object,

   publc class Contact {
        public string Given { get; set; }
        public string Surname{ get; set; } 
    }

然后,Web API将为您绑定对象

then Web API will bind the object for you

    public IHttpActionResult PostContacts(Contact data)
    {
        ApiResponse response = new ApiResponse();
        response.Data = data;    
        return Ok(response);
    }

如果仍然无法正常工作,则可能需要显示如何发布数据.

Still if it is not working, you might need to show how you are posting your data.

这篇关于在Web API 2操作中接收JSON格式的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆