Web Api 2是否在OWIN中间件中获得控制器和动作名称? [英] Web Api 2 get controller and action name in OWIN middleware?

查看:112
本文介绍了Web Api 2是否在OWIN中间件中获得控制器和动作名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一个自定义OWIN中间件中检索api控制器名称和api操作名称?我可以在像这样的消息处理程序内完成此操作:

How can I retrieve the api controller name and api action name inside a piece of custom OWIN middleware? I can do it inside of a message handler like so:

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中间件.如何在此代码中获取controllerName和actionName?

Update: Here is my current piece of OWIN middleware. How can I get the controllerName and actionName within this code?

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

推荐答案

您真的不能. OWIN中间件不了解Web Api.它只知道传递给它的环境.中间件的想法是,它独立于托管和应用程序平台.

You really can't. OWIN middleware does not know about Web Api. It only knows about the environment that is passed to it. The idea of middleware is that it is independent of the hosting and application platforms.

您没有提供要完成的工作的具体示例,因此可能有一种方法可以完成您要完成的工作.

You didn't provide a specific example of what you are trying to accomplish, so there might be a way of doing what you are trying to do.

更新为包含对上述声明的回复:

您可以撤消您想做的事情.金田OWIN环境可通过GetOwinEnvironmentExtension方法在Web Api中的HttpRequest上使用.您可以将环境变量添加到带有控制器名称和控制器内部方法的字典中,然后在Web api完成后调用中间件时使用该变量.很多重复的代码,但是可以.

You can reverse what you are trying to do. Kinda. The OWIN environment is available on the HttpRequest inside Web Api with the GetOwinEnvironmentExtension method. You could add an environment variable to the dictionary with the name of the controller and method inside the controller and then use that when your middleware is called after web api is finished. Lots of repetitive code, but it would work.

在调用方法之前,可能有一种拦截方法的方法.从@ mark-jones中查看答案,可能会为您提供一些帮助.

There is probably a way to intercept the method before it is called. Check out this answer from @mark-jones that might give you some insight to doing that.

希望有帮助.

这篇关于Web Api 2是否在OWIN中间件中获得控制器和动作名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆