写一个ActionFilter检测WebApi接口请求和响应

我们一般用日志记录每次Action的请求和响应,方便接口出错后排查,不过如果每个Action方法内都写操作日志太麻烦,而且客户端传递了错误JSON或XML,没法对应强类型参数,请求没法进入方法内,

把日志记录操作放在一个ActionFilter即可。

[AttributeUsageAttribute(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public class ApiActionAttribute : ActionFilterAttribute
{
    private string _requestId;
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        base.OnActionExecuting(actionContext);
        _requestId = DateTime.Now.Ticks.ToString();

        //获取请求数据
        Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result;
        string requestDataStr = "";
        if (stream != null && stream.Length > 0)
        {
            stream.Position = 0; //当你读取完之后必须把stream的读取位置设为开始
            using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
            {
                requestDataStr = reader.ReadToEnd().ToString();
            }
        }

        //[POST_Request] {requestid} http://dev.localhost/messagr/api/message/send {data}
        Logger.Instance.WriteLine("[{0}_Request] {1} {2}\r\n{3}", actionContext.Request.Method.Method, _requestId, actionContext.Request.RequestUri.AbsoluteUri, requestDataStr);
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnActionExecuted(actionExecutedContext);
        string responseDataStr = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;
        //[POST_Response] {requestid} {data}
        Logger.Instance.WriteLine("[{0}_Response] {1}\r\n{2}", actionExecutedContext.Response.RequestMessage.Method, _requestId, responseDataStr);
    }
}

_requestId 是用来标识请求的,根据它可以找到对应的Request与Response,便于排查。在Action上声明:

[Route("send_email")]
[HttpPost]
[ApiAction]
[ApiException]
public async Task<SendMessageResponseDto> Send(SendEmailMessageRequestDto dto)
{
    //...
}
时间: 2024-08-01 22:46:06

写一个ActionFilter检测WebApi接口请求和响应的相关文章

Java基础-接口.编写2个接口:InterfaceA和InterfaceB;在接口InterfaceA中有个方法void printCapitalLetter();在接口InterfaceB中有个方法void printLowercaseLetter();然 后写一个类Print实现接口InterfaceA和InterfaceB,要求 方法 实现输出大写英文字母表的功能,printLowerca

#34.编写2个接口:InterfaceA和InterfaceB:在接口InterfaceA中有个方法void printCapitalLetter():在接口InterfaceB中有个方法void printLowercaseLetter():然 后写一个类Print实现接口InterfaceA和InterfaceB,要求      方法 实现输出大写英文字母表的功能,printLowercaseLetter()方法实现输出小写英文 字母表的功能.再写一个主类E,在主类E的main方法中创建P

发送一个简单的http get 请求并且响应

问题 如何发送一个简单的HTTP GET请求并且取回相应的HTTP响应. 设计 创建一个WebClient类的实例,然后使用它的DownloadData()方法. 方案 string uri = "http://server/path/WebForm.aspx"; WebClient wc = new WebClient(); Console.WriteLine("Sending an HTTP GET request to " + uri); byte[] bRe

用flask写一个接单的接口

用falsk写一个简单的接口,这个接口的数据本来是爬虫爬取的数据,但是今天只写一个flask接口,数据就用测试数据好了. import random import re import time import requests import flask,json from flask import request server = flask.Flask(__name__) @server.route('/accessoriesName',methods = ['get','post']) def

WebApi接口请求失败,找不到资源。

WebApi开发接口,实现同步数据库的数据给安卓. public class UserInfoController : ApiControllerBase { private UserBLL userbll = new UserBLL(); /// <summary> /// 安卓同步用户信息接口 /// </summary> /// <param name="queryJson"></param> /// <returns>

用Flask写一个简单的通用接口

测试工作中,会需要测试人员自己写个接口,用于测试系统,下面的接口实现:请求该接口,接口返回该请求该接口时的所有请求信息 from flask import Flask, request app = Flask('test_api') @app.route('/get_request_info', methods=['post','get'])def get_request_info():    resp = {'params_data':'', 'headers':'', 'params_que

编写2个接口:InterfaceA和InterfaceB;在接口InterfaceA中有个方法void printCapitalLetter();在接口InterfaceB中有个方法void printLowercaseLetter();然 后写一个类Print实现接口InterfaceA和InterfaceB,要求printCapitalLetter()方法 实现输出大写英文字母表的功能,pri

package com.homework1; public interface InterfaceA { //声明抽象方法 void printCapitalLetter(); } package com.homework1; public interface InterfaceB { //声明抽象方法 void printLowercaseLetter(); } package com.homework1; public class Print implements InterfaceA, I

自己动手写一个iOS 网络请求库的三部曲[转]

代码示例:https://github.com/johnlui/Swift-On-iOS/blob/master/BuildYourHTTPRequestLibrary 开源项目:Pitaya,适合大文件上传的 HTTP 请求库:https://github.com/johnlui/Pitaya 本系列文章中,我们将尝试使用 NSURLSession 技术构建一个自己的网络请求库. NSURLSession 简介 NSURLSession 是 iOS7 引入的新网络请求接口,在 WWDC2013

从零开始写一个Tomcat(叁)--请求解析

挖坑挖了这么长时间也该继续填坑了,上文书讲到从零开始写一个Tomcat(贰)--建立动态服务器,讲了如何让服务器解析请求,分离servlet请求和静态资源请求,读取静态资源文件输出或是通过URLClassLoader找到我们请求的servlet,反射生成对应的实例,调用其service方法,传递初级解析的request和response,完成请求. 这很tomcat,but too simple 阅读本文,你将了解 连接器(connector),处理器(processor)逻辑分离 如何高效的解

【UE4实用技能】写一个异步回调的蓝图接口

在做系统功能的时候经常需要到服务器去下载图片然后再显示,蓝图已经提供了这个接口供大家使用: 如果没有别的其他需求,那这个接口就够用了. 不过我们的项目需要在这个接口的基础上加一些功能:1.本地缓存(不需要每次都请求)2.把图片存放到硬盘(不需要每次重启游戏都重新下载)3.设定一个文件数量阈值,超过这个值就删掉最早的文件4.判断一下路径,如果是本地的图片直接加载,网络图片加载(整合所有图片加载接口为唯一一个) 因为改动比较多所以不在DownloadImage这个接口上改,重新写一个类来处理.(具体