Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing current controller executing in DelegatingHandler

I was wondering if it's possible to access the controller being executed (or about to be executed) in the SendAsync method of the DelegatingHandler? I can't seem to figure out how to get access to it, and I figure it's because it executes outside of the controller execution...

Is it possible to refer to it?

like image 733
Brian Mains Avatar asked Oct 20 '12 01:10

Brian Mains


2 Answers

No, because message handlers operate on raw HttpRequestMessage or raw HttpResponseMessage (in case of continuations). So really, there is no concept of "current controller executing" with DelegatingHandlers since message handlers will be called before dispatching the request to the controller or (again, in the case of continuations) after the controller returns the reponse.

However, it really depends what you are trying to do.

If you want to know to which controller the request will end up getting routed, you can manually call the mechanism that would internally select the controllers.

public class MyHandler : DelegatingHandler
{
    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        var config = GlobalConfiguration.Configuration;
        var controllerSelector = new DefaultHttpControllerSelector(config);

        // descriptor here will contain information about the controller to which the request will be routed. If it's null (i.e. controller not found), it will throw an exception
        var descriptor = controllerSelector.SelectController(request);

        // continue
        return base.SendAsync(request, cancellationToken);
    }
}
like image 112
Filip W Avatar answered Oct 15 '22 23:10

Filip W


Extending the @GalacticBoy solution, it would be better to use

public class MyHandler : DelegatingHandler
{
    private static IHttpControllerSelector _controllerSelector = null;

    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        if (_controllerSelector == null)
        {
            var config = request.GetConfiguration();
            _controllerSelector = config.Services.GetService(typeof(IHttpControllerSelector)) as IHttpControllerSelector;
        }

        try
        {
            // descriptor here will contain information about the controller to which the request will be routed. If it's null (i.e. controller not found), it will throw an exception
            var descriptor = _controllerSelector.SelectController(request);


        }
        catch
        {
            // controller not found
        }

        // continue
        return base.SendAsync(request, cancellationToken);
    }
}
like image 32
Magic Avatar answered Oct 16 '22 01:10

Magic