How to receive json in ASP.NET web api?

后端 未结 3 1451
北海茫月
北海茫月 2020-12-18 08:51

I have an external company pushing data to one of our server, they are going to send JSON data. I need to create a POST api to receive it. This is what I have so far

相关标签:
3条回答
  • 2020-12-18 09:23

    In Web API you let the framework do most of the tedious serialization work for you. First amend your method to this:

    [HttpPost]
    public void PushSensorData(SensorData data)
    {
        // data and its properties should be populated, ready for processing
        // its unnecessary to deserialize the string yourself.
        // assuming data isn't null, you can access the data by dereferencing properties:
        Debug.WriteLine(data.Type);
        Debug.WriteLine(data.Id);
    }
    

    Create a class. To get you started:

    public class SensorData 
    {
        public SensorDataId Id { get; set; }
        public string Type { get;set; }
    }
    
    public class SensorDataId
    {
        public string Server { get; set; }
    }
    

    The properties of this class need to mirror the structure of your JSON. I leave it to you to finish adding properties and other classes to your model, but as written this model should work. The JSON values that don't correspond to your model should be thrown out.

    Now, when you call your Web API method, your sensor data will already be deserialized.

    For more information, see http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

    0 讨论(0)
  • 2020-12-18 09:32

    Your Web API model needs to be same as javascript request object

    For example,

    public class SomeRequest
        {
    
            public string data1{ get; set; }
            public string data2{ get; set; }
            public string data13{ get; set; }
    
        }
    

    In Javascript , your request object and javascript call should be like this

     var requestObj = {
                    "data1": data1,
                    "data2": data2,
                    "data3": data3,
    
                };
    

    And post url and requestObj in javascript

    Access in Web API like this

      public void PushSensorData(SomeRequest objectRequest)
            {
    objectRequest.data1
    objectRequest.data2
    objectRequest.data3
    
    0 讨论(0)
  • 2020-12-18 09:34

    Have you tried JSON.stringify(yourObject) (this is Javascript but any language has this kind of utility) before passing it to your web api?

    May I also point out your comment earlier, stating you're using a GET method because you can't get POST working? You should be careful in your planning because a GET method can only take so much space: if your object becomes larger you'll be forced to use a POST, so I'd suggest you take this approach right away.

    0 讨论(0)
提交回复
热议问题