从c#中的HTTPRequest中检索Request Payload值

时间:2014-06-26 10:10:39

标签: c# asp.net-mvc-4 asp.net-web-api httpwebrequest

我正在尝试实现自己的LRS以保存TinCanAPI语句,为了做到这一点,我需要检索请求有效负载中发送的值,该值存储学习活动语句的详细信息。 在开发人员工具中查看我的WebAPI调用时,我可以看到所需的值,但我无法使用Request对象找到它们。

如何从Request对象中检索Request Payload变量?我已经尝试了请求对象并查看了内容和属性字段,但我似乎无法在C#中看到要引用的Request Payload属性。我的有效载荷如下所示:

{
    "id": "d3d9aa2a-5f20-4303-84c3-1f6f5b4e9236",
    "timestamp": "2014-06-26T11:00:41.432Z",
    "actor": {
        "objectType": "Agent",
        "mbox": "mailto:name@company.com",
        "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."
            }
        }
    }
}

我尝试过使用:

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

3 个答案:

答案 0 :(得分:0)

我能够通过更改我的WebAPI控制器来检索发送的语句值,如下所示:

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;

   ...................

答案 1 :(得分:0)

 try {
                //String payloadRequest = getBody(request);
                // System.out.println("payloadRequest : "+payloadRequest);
                StringBuilder buffer = new StringBuilder();
                 BufferedReader reader = request.getReader();
                 String line;
                 while ((line = reader.readLine()) != null) {
                     buffer.append(line);
                 }
                 String data = buffer.toString();
                 System.out.println("payloadRequest : "+data);
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

答案 2 :(得分:-1)

试试这个:

var value = Request["var_name"];