简体   繁体   中英

How to enable WebApi DelegatingHandler via web.config

In order to log the JSON of each WebApi request/response I have created a custom DelegatingHandler and added this to the MessageHandlers collection in WebApiConfig.cs and it works great.

In future though, I'd like to be able to enable this handler on other WebApi applications via web.config without having to actually modify WebApiConfig.cs .

By way of clarification, what I'm trying to achieve is analogous to what was possible in WCF where you could create a completely separate dll, drop it into the bin folder of a WCF service and add it into the WCF pipeline solely by editing the web.config file without having to modify the source of the service at all.

Is this possible in WebApi or can a custom DelegatingHandler only be added via code at runtime?

After a bit of research I am answering my own question. It seems like this is not possible without having to modify the source of the target application. It might be possible to dynamically load or inject such a handler at startup if some thought was given during the writing of the application and knew to look for it. Another possible solution would be to create the logging handler as a nuget package and when the nuget package is installed into the target application the installer would add the dll and also create a WebActivator hook that added the handler to the MessagingHandlers collection in PostApplicationStartMethod . This might be the approach that involves that least amount of manual code change, but would still require recompilation and re-deployment of the target app.

Modify the handler to check the config and perform its function if enabled otherwise just let the request pass through. if being used for logging make sure it is added early in the pipeline. Look into using middle-ware if possible.

public class LoggingHandler : DelegatingHandler {
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
        var appSetting = ConfigurationManager.AppSettings["LoggingHandlerEnabled"];
        var enabled = true;
        bool.TryParse(appSetting, out enabled);

        if(enabled) {
            //...Extract and log request
            LogRequest(request);
        }

        // Execute the request and get the response
        var response = await base.SendAsync(request, cancellationToken);

        if(enabled) {
            //...Extract details from response for logging
            LogResponse(response);
        }

        return response;
    }

    private void LogRequest(HttpRequestMessage request) {
        //... code removed for brevity
    }

    private void LogResponse(HttpResponseMessage response) {
        //... code removed for brevity
    }
}

With that in place then there would be no further need to modify any more code to enable/disable the handler. Update the config file and the handler will respect the setting.

Tracing in ASP.NET Web API 2

From the Tools menu, select Library Package Manager, then Package Manage Console.

In the Package Manager Console window, type the following commands.

Install-Package Microsoft.AspNet.WebApi.Tracing
Update-Package Microsoft.AspNet.WebApi.WebHost

The first command installs the latest Web API tracing package. It also updates the core Web API packages. The second command updates the WebApi.WebHost package to the latest version.

Open the file WebApiConfig.cs in the App_Start folder. Add the following code to the Register method.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // New code
        config.EnableSystemDiagnosticsTracing();

        // Other configuration code not shown.
    }
}

This code adds the SystemDiagnosticsTraceWriter class to the Web API pipeline. The SystemDiagnosticsTraceWriter class writes traces to System.Diagnostics.Trace .

To see the traces, run the application in the debugger. In the browser, navigate to /api/values .

The trace statements are written to the Output window in Visual Studio. (From the View menu, select Output).

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM