IT박스

asp.net webapi 2 요청 및 응답 본문을 데이터베이스에 기록해야합니다.

itboxs 2020. 8. 25. 07:48
반응형

asp.net webapi 2 요청 및 응답 본문을 데이터베이스에 기록해야합니다.


IIS에서 호스팅되는 Microsoft Asp.net WebApi2를 사용하고 있습니다. 요청 본문 (xml 또는 json)과 각 게시물에 대한 응답 본문을 기록하고 싶습니다.

이 프로젝트 또는 게시물을 처리하는 컨트롤러에는 특별한 것이 없습니다. 필요한 경우가 아니면 nLog, elmah, log4net 또는 webapi의 내장 추적 기능과 같은 로깅 프레임 워크를 사용하는 데 관심이 없습니다.

로깅 코드를 어디에 넣을지, 수신 및 발신 요청 및 응답에서 실제 json 또는 xml을 얻는 방법을 알고 싶습니다.

내 컨트롤러 게시 방법 :

public HttpResponseMessage Post([FromBody])Employee employee)
{
   if (ModelState.IsValid)
   {
      // insert employee into to database
   }

}

나는 DelegatingHandler. 그러면 컨트롤러의 로깅 코드에 대해 걱정할 필요가 없습니다.

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;
    }
}

Trace.WriteLine로깅 코드로 바꾸고 다음 WebApiConfig같이 핸들러를 등록하십시오 .

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

다음은 메시지 처리기에 대한 전체 Microsoft 설명서입니다 .


모든 WebAPI 메서드 호출에 대한 요청 / 응답 로깅을 일반적으로 처리하는 방법에는 여러 가지가 있습니다.

  1. ActionFilterAttribute: 사용자 정의를 작성 ActionFilterAttribute하고 로깅을 활성화하기 위해 컨트롤러 / 액션 메서드를 장식 할 수 있습니다.

    단점 : 모든 컨트롤러 / 방법을 장식해야합니다 (여전히 기본 컨트롤러에서 할 수 있지만 교차 절단 문제는 해결되지 않습니다.

  2. BaseController거기에서 로깅을 무시 하고 처리합니다.

    단점 : 컨트롤러가 사용자 지정 기본 컨트롤러에서 상속 할 것으로 예상 / 강제합니다.

  3. 사용 DelegatingHandler.

    장점 : 여기서는이 접근 방식으로 컨트롤러 / 방법을 건드리지 않습니다. 위임 처리기는 격리되어 있으며 요청 / 응답 로깅을 정상적으로 처리합니다.

For more indepth article, refer this http://weblogs.asp.net/fredriknormen/log-message-request-and-response-in-asp-net-webapi.


One of the option you have is using creating a action filter and decorating your WebApiController/ApiMethod with it.

Filter Attribute

public class MyFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.Request.Method == HttpMethod.Post)
            {
                var postData = actionContext.ActionArguments;
                //do logging here
            }
        }
    }

WebApi controller

[MyFilterAttribute]
public class ValuesController : ApiController{..}

or

[MyFilterAttribute]
public void Post([FromBody]string value){..}

Hope this helps.


Getting access to request message is easy. Your base class, ApiController contains .Request property, which, as name suggests, contains the request in parsed form. You simply examine it for whatever you're looking to log and pass it to your logging facility, whichever it may be. This code you can put in the beginning of your action, if you need to do it for just one or a handful.

If you need to do it on all actions (all meaning more than a manageable handful), then what you can do is override .ExecuteAsync method to capture every action call for your controller.

public override Task<HttpResponseMessage> ExecuteAsync(
    HttpControllerContext controllerContext,
    CancellationToken cancellationToken
)
{
    // Do logging here using controllerContext.Request
    return base.ExecuteAsync(controllerContext, cancellationToken);
}

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

반응형