WEB API使用复杂参数“jobject”

时间:2016-03-31 00:17:17

标签: c# asp.net asp.net-web-api2

我正在尝试为通话创建示例

public HttpResponseMessage Post([FromBody]JObject value)

按照此处描述的示例ASP.NET Web API Help Page Part 2: Providing custom samples on the Help Page 我设置了文件“HelpPageConfig.cs”

config.SetSampleResponse("test",
                         new MediaTypeHeaderValue("application/json"), 
                         "Eventos",
                         "Post", 
                         "value");

我的控件名为“EventosController.cs”,仅在访问示例中的页面时显示“not available sample”

我要展示的样本如下:

{
 "field1":"value1",
 "field2":"value2",
 "field3":"value3",
 "field4":"value4",
 "field5":"value5",
 "field6":"value6",
 "field7":"value7",
}

还有什么需要做的?

1 个答案:

答案 0 :(得分:1)

您的问题是您正在显示示例响应,而不是请求。对于完整的帮助页面,您可能需要添加一个示例请求(对于此控制器和操作,或者如果您打算对类型使用相同的示例,则为类型)

HelpPageConfig中的内容如下:

public static void Register(HttpConfiguration config)
{
    var requestSample = @"{
field1: 'value1',
field2: 'value2'
}";

    //if there would be just 1 sample for all JObject types:
    config.SetSampleForType(
        requestSample,
        new MediaTypeHeaderValue("application/json"),
        typeof(JObject));

    //if you want to write the specific sample for each method/media type
    config.SetSampleRequest(requestSample, 
                            new MediaTypeHeaderValue("text/json"), 
                            "Eventos", 
                            "Post");
    config.SetSampleRequest(requestSample, 
                            new MediaTypeHeaderValue("application/x-www-form-urlencoded"), 
                            "Eventos", 
                            "Post");
    config.SetSampleRequest(requestSample, 
                            new MediaTypeHeaderValue("application/json"), 
                            "Eventos", 
                            "Post");

    //and finally, response sample
    var responseSample = "my response sample response";
    config.SetSampleResponse(responseSample, 
                             new MediaTypeHeaderValue("application/x-www-form-urlencoded"), 
                             "Eventos", 
                             "Post", 
                             "value");
}