Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

c# - Intercept all WebApi calls before the route matching occurs

I am looking for a way to intercept/grab the request being made before matching to a route. For example, I have multiple controllers and routes set up, but I want some mechanism in which will be hit before the route method is hit. It would be highly preferable if this mechanism were able to get the route params that were sent.

I have been unable to find something similar to what I am looking for (but perhaps not being well versed in Web API I am searching with the wrong keywords).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you need is action filters. You can apply action filters directly to controllers as attributes, the caveat with Action filters is that at this point the controller route is already known but you can still control (very much like AOP) if the action method can be executed or not:

ASP.NET Web API ActionFilter example

Look at how you can use an action filter, in this case for logging:

public class LogActionFilter : ActionFilterAttribute 
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        Log(actionExecutedContext.ActionContext.RequestContext.RouteData);

        base.OnActionExecuted(actionExecutedContext);
    }

    private void Log(System.Web.Http.Routing.IHttpRouteData httpRouteData)
    {
        var controllerName = "controller name";
        var actionName = "action name";
        var message = String.Format("controller:{0}, action:{1}", controllerName, actionName);

    Debug.WriteLine(message, "Action Filter Log");
    }
}

How to log which action method is executed in a controller in webapi

You can also use message handlers, which are executed before the controller is resolved:

HTTP Message Handlers in ASP.NET Web API


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...