Skip to main content

๐Ÿ‘ฉโ€๐Ÿ’ป Web API ๆ””ๆˆชๅ™จ

ๅฏฆๅšโ€‹

using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

public class SampleApiInterceptorAttribute : ActionFilterAttribute
{
public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
// ๅœจๅŸท่กŒๆ“ไฝœไน‹ๅ‰ๆ””ๆˆช่ซ‹ๆฑ‚
// ๅฏไปฅๅœจ้€™่ฃก่จ˜้Œ„่ซ‹ๆฑ‚่ณ‡่จŠ๏ผŒ้€ฒ่กŒ้ฉ—่ญ‰็ญ‰ๆ“ไฝœ
string requestInfo = $"{DateTime.Now}: Request from {actionContext.Request.RequestUri}";
Console.WriteLine(requestInfo);

// ็นผ็บŒ่™•็†่ซ‹ๆฑ‚
await base.OnActionExecutingAsync(actionContext, cancellationToken);
}

public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
// ๅœจๅŸท่กŒๆ“ไฝœไน‹ๅพŒๆ””ๆˆชๅ›žๆ‡‰
// ๅฏไปฅๅœจ้€™่ฃก่จ˜้Œ„ๅ›žๆ‡‰่ณ‡่จŠ๏ผŒ้€ฒ่กŒๅพŒ็บŒ่™•็†็ญ‰ๆ“ไฝœ
string responseInfo = $"{DateTime.Now}: Response to {actionExecutedContext.Request.RequestUri}";
Console.WriteLine(responseInfo);

// ็นผ็บŒ่™•็†ๅ›žๆ‡‰
await base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
}
}

ไฝฟ็”จโ€‹

ๆŒ‡ๅฎš Controllerโ€‹

[SampleApiInterceptor]
public class MyController : ApiController
{
// ......
}

ๅ…จๅŸŸ่จปๅ†Šโ€‹

  • ๅœจ็จ‹ๅผ็š„่ตทๅง‹้ปž่จญๅฎš
 GlobalConfiguration.Configuration.Filters.Add(new SampleApiInterceptorAttribute());