Search code examples
c#asp.net-mvc-4asp.net-web-apihttpwebrequest

Retrieving the Request Payload values from a HTTPRequest in c#


I am attempting to implement my own LRS for saving TinCanAPI statements and in order to do this I need to retrieve the values sent in the Request Payload which stores the details of the learning activity statement. When viewing my WebAPI call in developer tools I can see the required values but I have been unable to find them using the Request object.

How Can I retrieve the Request Payload variables from the Request object? I have tried the request object and looked in the Content and Properties fields but I cannot seem to see a Request Payload property to reference in C#. My payload looks as follows:

{
    "id": "d3d9aa2a-5f20-4303-84c3-1f6f5b4e9236",
    "timestamp": "2014-06-26T11:00:41.432Z",
    "actor": {
        "objectType": "Agent",
        "mbox": "mailto:[email protected]",
        "name": "My Name"
    },
    "verb": {
        "id": "http://adlnet.gov/expapi/verbs/attempted",
        "display": {
            "und": "attempted"
        }
    },
    "context": {
        "extensions": {
            "http://tincanapi.com/JsTetris_TCAPI/gameId": "5686f104-3301-459d-9487-f84af3b3915c"
        },
        "contextActivities": {
            "grouping": [
                {
                    "id": "http://tincanapi.com/JsTetris_TCAPI",
                    "objectType": "Activity"
                }
            ]
        }
    },
    "object": {
        "id": "http://tincanapi.com/JsTetris_TCAPI",
        "objectType": "Activity",
        "definition": {
            "type": "http://adlnet.gov/expapi/activities/media",
            "name": {
                "en-US": "Js Tetris - Tin Can Prototype"
            },
            "description": {
                "en-US": "A game of tetris."
            }
        }
    }
}

I have tried using:

var test1 = Request.ToString(); **EMPTY STRING**

var test1 = Request.Content.ReadAsStringAsync().Result; **EMPTY STRING**

var test2 = Request.Content.ReadAsFormDataAsync().Result; **THROWS FORMATTER ERROR DESPITE config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); added in the webapiconfig.cs

Solution

  • I was able to retrieve the sent statement values by changing my WebAPI controller as follows:

    public void Put([FromBody]TinCan.Statement statement)
    {
       var actor = statement.actor;
       var context = statement.context;
       var target = statement.target;
       var timestamp = statement.timestamp;
       var verb = statement.verb;
    
       ...................