在Web API控制器中接收Json字符串 [英] Receiving Json string in Web API controller

查看:67
本文介绍了在Web API控制器中接收Json字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我从WPF应用程序中输入的Json字符串,

  {{原产国":美国",商品":苹果",品种":绿色","Upcs":[{"timestamp":"2017-09-19T21:05:12.8550708 + 05:30",值":"038452735329R5"},{"timestamp":"2017-09-19T21:05:12.8550708 + 05:30",值":"038452735330R5"}],"ipAddress":"127.0.0.1","lat":"155.00",全部":"101.14","long":"-202.00","onBehalfOf":"679","ClientVersion":"10.0.7","submittedBy":"679"}} 

我已经在.net(VS2015)中创建了Rest Api2应用,我想在我新创建的API中接收上述JSON字符串以进行进一步处理.

在WPF中,我正在使用WebClient发送Json字符串.

下面是我尝试接收Json字符串的API函数,

  [Route("api/events/getevents/{events}/{producerId}")][HttpGet,HttpPost]公共异步Task< IHttpActionResult>GetEvents(字符串事件,字符串producerId){尝试{await _getEventsAction.GetEventJson(events,producerId).ConfigureAwait(false);返回Ok(成功");}捕获(前AggregateException){返回Ok(new {ex.InnerException.Message,Success = false,ex.StackTrace,Exception = ex});}抓住(前例外){返回Ok(new {ex.Message,Success = false,ex.StackTrace,Exception = ex});}} 

在本地运行该应用程序后,我通过证明以下值(即对于events ="testing"和producerId ="554")的最终值如下所示,在网络浏览器中测试了api,

  1. 我想知道,我开发的API函数正确接收了Json字符串.如果有什么好的方法,请指导我.

  2. 我想知道通过输入Json字符串来测试此API的更好的方法是什么.

  3. 是否可以在api中将Json作为对象接收.

请帮助我编写此API来接收Json字符串或Json对象.

谢谢

解决方案

通常,在需要发送JSON的情况下,应发出POST/PUT请求并在请求正文中发送JSON.

要这样做:

  1. 您需要创建与JSON匹配的模型:

      [DataContract]公共类MyModel{[DataMember(名称=原产国")]公共字符串CountryOfOrigin {get;放;}[DataMember(名称=商品")]公共字符串商品{get;放;}//其他栏位} 

    另外,请注意,我将DataContract和DataMember属性用作输入JSON字段未规范化(字段具有空格和大小写不同(camelCase和CamelCaps).

    如果您将JSON标准化为camelCase,则可以删除DataContract和DataMember属性.

  2. 将控制器中的操作更改为:

      [Route("api/events/getevents/{events}/{producerId}")][HttpPost]公共异步Task< IHttpActionResult>GetEvents(字符串事件,字符串producerId,[FromBody] MyModel模型){//您的代码} 

    最后一个模型"参数将使用您从客户端发送的值填充.

    [HttpPost] 属性表示此操作仅对POST请求可用.

    [FromBody] 属性指示Web API应该从请求的正文中获取模型.

Following is my Json input string from WPF app,

{{
  "Country of Origin": "UNITED STATES",
  "Commodity": "APPLES",
  "Variety": "Green",
  "Upcs": [
    {
      "timestamp": "2017-09-19T21:05:12.8550708+05:30",
      "value": "038452735329R5"
    },
    {
      "timestamp": "2017-09-19T21:05:12.8550708+05:30",
      "value": "038452735330R5"
    }
  ],
  "ipAddress": "127.0.0.1",
  "lat": "155.00",
  "Lot": "101.14",
  "long": "-202.00",
  "onBehalfOf": "679",
  "ClientVersion": "10.0.7",
  "submittedBy": "679"
}}

I have created a Rest Api2 app in .net (VS2015) and i want to receive the above JSON string in my newly created API for furthur processing.

In WPF, i am using WebClient to send the Json string.

Below is the API function I tried to receive the Json string,

    [Route("api/events/getevents/{events}/{producerId}")]
    [HttpGet, HttpPost]
    public async Task<IHttpActionResult> GetEvents(string events, string producerId)
    {
        try
        {
            await _getEventsAction.GetEventJson(events, producerId).ConfigureAwait(false);
            return Ok("Success");
        }
        catch (AggregateException ex)
        {
            return Ok(new { ex.InnerException.Message, Success = false, ex.StackTrace, Exception = ex });
        }
        catch (Exception ex)
        {
            return Ok(new { ex.Message, Success = false, ex.StackTrace, Exception = ex });
        }
    }

After running the app in local, i tested the api in web browser by proving the following values that is, for events="testing" and producerId="554", the final endpoint looks like below,

http://localhost:18572/api/events/getevents/testing/554 -> this case the endpoint works fine in browser. But for testing the above api, instead of testing, when i input the whole Json string in browser web address, browser is showing the error as "A potentially dangerous Request.Path value was detected from the client (:)." . This is due to the double quotes and colon in between the json string, browser is showing the error page.

Screen below,

  1. I want to know, the API function what i developed is correct to receive the Json string. If any good way please guide me.

  2. May i know what are the better way i can test this API by input the Json string.

  3. Is it possible to receive the Json as object in api.

Please help me in writing this API to receive the Json string or Json object.

Thanks

解决方案

Normally, in cases when you need to send JSON, you should make POST/PUT request and send JSON in the request body.

To do so:

  1. You need to create model which matches your JSON:

    [DataContract]
    public class MyModel
    {
        [DataMember(Name = "Country of Origin")]
        public string CountryOfOrigin { get; set; }
    
        [DataMember(Name = "Commodity")]
        public string Commodity { get; set; }
    
        // other fields
    }
    

    Also, note I used DataContract and DataMember attributes as incoming JSON fields not normalized (fields has spaces and different case (camelCase and CamelCaps)).

    If you will normalize your JSON to camelCase, you may remove DataContract and DataMember attributes.

  2. Change action in controller to:

    [Route("api/events/getevents/{events}/{producerId}")]
    [HttpPost]
    public async Task<IHttpActionResult> GetEvents(string events, string producerId, [FromBody] MyModel model)
    {
        // your code
    }
    

    Last "model" parameter will be populated with values you send from client.

    [HttpPost] attribute indicates that this action will be available only with POST requests.

    [FromBody] attribute indicates that Web API should take model from request's body.

这篇关于在Web API控制器中接收Json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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