如何在WebAPI中访问序列化的JSON

Noe*_*oel 2 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Bad*_*dri 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public HttpResponseMessage PostCustomer(Customer customer)
{
    string json = (string)Request.Properties["json"];
}
Run Code Online (Sandbox Code Playgroud)