Asp.net web api 如何访问WebAPI中的序列化JSON

Asp.net web api 如何访问WebAPI中的序列化JSON,asp.net-web-api,Asp.net Web Api,如何从WebApi中的控制器方法访问JSON?例如,下面我希望访问作为参数传入的反序列化客户和序列化客户 public HttpResponseMessage PostCustomer(Customer customer) { if (ModelState.IsValid) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, customer

如何从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);
        }
    }

您将无法在控制器中获取JSON。在ASP.NET Web API管道中,绑定发生在操作方法执行之前。媒体格式化程序将读取请求体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);
    }
}

您无法获取已解析的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.
}
公共异步任务后客户(客户)
{
var json=Newtonsoft.json.JsonConvert.DeserializeObject(等待这个.Request.Content.ReadAsStringAsync());
///您可以反序列化到所需的任何对象,或者只是一个字典,以便检查键值对。
}

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

然而,我发现OWIN管道先于WebAPI管道。因此,通过将OWIN添加到Web API项目并创建自定义中间件类,您可以在请求到达Web API管道之前和离开Web API管道之后处理请求,这非常方便。一定会给你带来你想要的结果


希望这能有所帮助。

我不确定这是否有效,因为流只能读取一次,因为这种情况发生在媒体格式化程序中,我决定尝试在其中执行。最后,我暂时放弃了这个想法。如果我想在解析之前获得原始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.
}