码迷,mamicode.com
首页 > 其他好文 > 详细

get the request body of all quests before handle it

时间:2019-01-18 19:51:42      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:mic   prot   ESS   ase   sof   asp   view   pre   RoCE   

https://stackoverflow.com/questions/23660340/need-to-log-asp-net-webapi-2-request-and-response-body-to-a-database

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers

 拦截api的请求,并进行处理

I would recommend using a DelegatingHandler. Then you will not need to worry about any logging code in your controllers.

public class LogRequestAndResponseHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // log request body
        string requestBody = await request.Content.ReadAsStringAsync();
        Trace.WriteLine(requestBody);

        // let other handlers process the request
        var result = await base.SendAsync(request, cancellationToken);

        if (result.Content != null)
        {
            // once response body is ready, log it
            var responseBody = await result.Content.ReadAsStringAsync();
            Trace.WriteLine(responseBody);
        }

        return result;
    }
}

Just replace Trace.WriteLine with your logging code and register the handler in WebApiConfig like this:

config.MessageHandlers.Add(new LogRequestAndResponseHandler());

 

get the request body of all quests before handle it

标签:mic   prot   ESS   ase   sof   asp   view   pre   RoCE   

原文地址:https://www.cnblogs.com/chucklu/p/10289197.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!