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 메서드 호출에 대한 요청 / 응답 로깅을 일반적으로 처리하는 방법에는 여러 가지가 있습니다.
ActionFilterAttribute
: 사용자 정의를 작성ActionFilterAttribute
하고 로깅을 활성화하기 위해 컨트롤러 / 액션 메서드를 장식 할 수 있습니다.단점 : 모든 컨트롤러 / 방법을 장식해야합니다 (여전히 기본 컨트롤러에서 할 수 있지만 교차 절단 문제는 해결되지 않습니다.
BaseController
거기에서 로깅을 무시 하고 처리합니다.단점 : 컨트롤러가 사용자 지정 기본 컨트롤러에서 상속 할 것으로 예상 / 강제합니다.
사용
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);
}
'IT박스' 카테고리의 다른 글
C # UTF-8에서 ISO-8859-1 (Latin1) H로 문자열 변환 (0) | 2020.08.25 |
---|---|
다중 레이어 퍼셉트론 (MLP) 아키텍처 : 은닉층 수와 은닉층 크기 선택 기준? (0) | 2020.08.25 |
SQL에서 복합 기본 키를 어떻게 정의 할 수 있습니까? (0) | 2020.08.25 |
dapper.net에서 트랜잭션을 사용하는 방법은 무엇입니까? (0) | 2020.08.25 |
Swift readonly 외부, readwrite 내부 속성 (0) | 2020.08.25 |