Web Api 2如何在OWIN中间件中获取控制器和动作名称?

3
我该如何在自定义的OWIN中间件中检索API控制器名称和API操作名称?我可以在消息处理程序中这样做:
var config = request.GetConfiguration();
var routeData = config.Routes.GetRouteData(request);
var controllerContext = new HttpControllerContext(config, routeData, request);
request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
controllerContext.RouteData = routeData;
var controllerDescriptor = new
DefaultHttpControllerSelector(config).SelectController(request);
controllerContext.ControllerDescriptor = controllerDescriptor;
var actionMapping = new ApiControllerActionSelector().SelectAction(controllerContext);

//controller name
controllerDescriptor.ControllerName
//action name
actionMapping.ActionName

更新: 这是我当前的OWIN中间件。在这段代码中,如何获取控制器名称和操作名称?

using AppFunc = Func<IDictionary<string, object>, Task>;

public class LoggingMiddleware
{
    private readonly AppFunc _next;
    private static readonly ILog RequestApiLogger = LogManager.GetLogger("RequestApiPacketLogger");
    private static readonly ILog ResponseApiLogger = LogManager.GetLogger("ResponseApiPacketLogger");

    public LoggingMiddleware(AppFunc next)
    {
        _next = next;
    }

    public async Task Invoke(IDictionary<string, object> environment)
    {
        var correlationId = Guid.NewGuid();
        IOwinContext context = new OwinContext(environment);

        // Buffer the request (body is a string, we can use this to log the request later
        var requestBody = new StreamReader(context.Request.Body).ReadToEnd();
        var requestData = Encoding.UTF8.GetBytes(requestBody);
        context.Request.Body = new MemoryStream(requestData);

        // Buffer the response
        var responseBuffer = new MemoryStream();
        var responseStream = context.Response.Body;
        context.Response.Body = responseBuffer;

        // add the "http-tracking-id" response header so the user can correlate back to this entry
        var responseHeaders = (IDictionary<string, string[]>)environment["owin.ResponseHeaders"];
        responseHeaders["http-tracking-id"] = new[] { correlationId.ToString("d") };

        IDictionary<string, string[]> responseHeadersClone = new Dictionary<string, string[]>(responseHeaders);

        //invoke the next piece of middleware in the pipeline
        await _next.Invoke(environment);

        // rewind the request and response buffers and record their content
        responseBuffer.Seek(0, SeekOrigin.Begin);
        var reader = new StreamReader(responseBuffer);
        var responseBody = await reader.ReadToEndAsync();

        // log the request/response as long at it wasn't preflight
        if (context.Request.Method.ToUpper() != "OPTIONS")
        {
            RequestApiLogger.LogHttpRequestAsync(context, correlationId, requestBody);
            ResponseApiLogger.LogHttpResponseAsync(context, correlationId, responseBody, responseHeadersClone);
        }

        // You need to do this so that the response we buffered is flushed out to the client application.
        responseBuffer.Seek(0, SeekOrigin.Begin);
        await responseBuffer.CopyToAsync(responseStream);
    }
}
1个回答

3
你确实无法这样做。OWIN中间件并不知道Web Api的存在,只知道传递给它的环境。中间件的理念是独立于托管和应用程序平台。
你没有提供你要达成什么具体目标,所以可能有一种实现你想做的事情的方法。
更新包括对上述语句的回复:
你可以反转你想要做的事情。在Web API内部的HttpRequest中使用GetOwinEnvironmentExtension方法可以获取OWIN环境。您可以向字典中添加一个环境变量,其中包含控制器和控制器内方法的名称,并在Web API完成后调用中间件时使用该变量。虽然代码重复很多,但它可以工作。
可能有一种在调用方法之前拦截方法的方法。查看@mark-jones 的答案可能会给您一些启示。
希望能帮到您。

我更新了我的问题,展示了我的当前日志中间件。我正在尝试获取ControllerName和ActionName,以便在我的日志表中包含这些字段,以获得更好的可追溯性。 - BBauer42

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接