如何在Web API中访问序列化的JSON

时间:2013-08-04 00:02:34

标签: asp.net-web-api

如何从WebApi中的控制器方法访问JSON?例如,我想要访问作为参数传入的反序列化客户和序列化客户。

public HttpResponseMessage PostCustomer(Customer customer)
{
    if (ModelState.IsValid)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, customer);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = customer.Id }));
            return response;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }

3 个答案:

答案 0 :(得分:5)

您将无法在控制器中获取JSON。在ASP.NET Web API管道中,绑定在action方法执行之前发生。媒体格式化程序将读取请求主体JSON(它是一次性读取流),并在执行到您的操作方法时清空内容。但是如果你在绑定之前从管道中运行的组件读取JSON,比如说一个消息处理程序,你就可以像这样阅读它。如果必须获取JSON in action方法,则可以将其存储在属性字典中。

public class MessageContentReadingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
                                  HttpRequestMessage request,
                                      CancellationToken cancellationToken)
    {
        var content = await request.Content.ReadAsStringAsync();

        // At this point 'content' variable has the raw message body
        request.Properties["json"] = content;

        return await base.SendAsync(request, cancellationToken);
    }
}

从action方法中,您可以检索这样的JSON字符串:

public HttpResponseMessage PostCustomer(Customer customer)
{
    string json = (string)Request.Properties["json"];
}

答案 1 :(得分:0)

您无法获取已解析的JSON,但您可以获取内容并自行解析。试试这个:

public async Task PostCustomer(Customer customer)
{
    var json = Newtonsoft.Json.JsonConvert.DeserializeObject(await this.Request.Content.ReadAsStringAsync());

    ///You can deserialize to any object you need or simply a Dictionary<string,object> so you can check the key value pairs.
}

答案 2 :(得分:0)

我试图做一些非常相似的事情,但是无法找到一种方法将处理程序直接注入到适当位置的Web API中。似乎委派的消息处理程序介于反序列化/序列化步骤和路由步骤之间(他们没有在所有这些Web API管道图中显示它们)。

但是我发现OWIN管道在Web API管道之前。因此,通过将OWIN添加到Web API项目并创建自定义中间件类,您可以在它们到达Web API管道之前以及离开Web API管道之后处理请求,这非常方便。肯定会得到你正在寻找的结果。

希望这有帮助。