创建自定义委托处理程序

时间:2014-03-09 17:45:09

标签: c# logging asp.net-web-api log4net

我想在我的asp.net web api中添加一个自定义委托处理程序。这个处理程序的目的是检查我的请求的内容,并在它们继续进入请求管道之前验证它们的某些条件......我还想在这个入口点注销请求。

但是,在管道中传递的request.content是system.web.http.webhost.httpcontrollerhandler.lazystreamcontent - 在MSDN中查找此类型不会显示如何反序列化或查看请求内容 - 当我尝试从流中读取内容,我留下了一个空字符串。见例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace Haxy.Pencilthis.Api.MVC.Handlers
{
    public class ContentValidationHandler : DelegatingHandler
    {

        private static log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            Stream strea = new MemoryStream();
            request.Content.CopyToAsync(strea);
            StreamReader reader = new StreamReader(strea);
            String res = reader.ReadToEnd();
            Log.Info("request content: " + res);
            return base.SendAsync(request, cancellationToken);

            //
        }

    }
}

1 个答案:

答案 0 :(得分:4)

没有返回res的原因是流位置设置为Request内容的结尾,而不是开头。此外,响应是错误的,因为没有正确等待base.SendAsync方法。

以下正确实施:

public class ContentValidationHandler : DelegatingHandler
{

    private static log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
    {

        var response = await base.SendAsync(request, cancellationToken);


        Stream strea = new MemoryStream();
        await request.Content.CopyToAsync(strea);
        strea.Position = 0;
        StreamReader reader = new StreamReader(strea);
        String res = reader.ReadToEnd();
        Log.Info("request content: " + res);

        return response;







        //
    }





}