WebApi – MessageHandlers – Pass request parameter to context

Each handler has a chance to examine and/or modify the request before passing it to the next handler in the chain, and to examine and/or modify the response it receives from the next handler. Typically, the last handler in the pipeline is the HttpClientHandler, which communicates directly with the network.
src – https://thomaslevesque.com/2016/12/08/fun-with-the-httpclient-pipeline/

ref – https://www.codeproject.com/Articles/1250932/Logging-and-Exception-handling-Versioning-in-ASP-N

//Global.asax.cs
public class WebApplication : System.Web.HttpApplication
{
	protected void Application_Start()
	{
		GlobalConfiguration.Configure(WebApiConfig.Register);
		RouteConfig.RegisterRoutes(RouteTable.Routes);

		MvcHandler.DisableMvcResponseHeader = true;
	}
}
	
//WebApi.Config.cs
public static class WebApiConfig
{
	public static void Register(HttpConfiguration config)
	{
		config.EnableCors();

		/* ATTACH MULTI GLOBAL EXCEPTION LOGGER*/
		config.Services.Add(typeof(IExceptionLogger),
							new GlobalExceptionLogger(LogMedia.MSSQL)
							);

		config.Services.Add(typeof(IExceptionLogger),
				new GlobalExceptionLogger(LogMedia.TXT)
				);
		/* ATTACH MULTI GLOBAL EXCEPTION LOGGER*/


		config.MessageHandlers.Add(new LogHandler());
		config.MessageHandlers.Add(new AuthHandler());
		config.MessageHandlers.Add(new RequestHandler());
	}
}
	


//LogHandler.cs
public class LogHandler : DelegatingHandler
{
	protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
												   CancellationToken cancellationToken)
	{
		Task<Stream> obj = request.Content.ReadAsStreamAsync();
		var result = obj.Result;
		result.Seek(0, SeekOrigin.Begin);
		var reader = new StreamReader(result, Encoding.UTF8);

		string jsonBody = reader.ReadToEnd();

		//The HttpRequestMessage class contains a dictionary "Properties" that you could use to store infos
		//https://stackoverflow.com/questions/16418632/is-it-possible-to-pass-data-from-delegatinghandler-to-controller-in-asp-net-web
		request.Properties.Add("test", jsonBody);

		//return stream to start for the other MessageHandlers 🙂
		result.Seek(0, SeekOrigin.Begin);

            return base.SendAsync(request, cancellationToken)
                .ContinueWith(task =>
                {
                    return task.Result;
                });

	}
}

//SystemException.cs
public class GlobalExceptionLogger : ExceptionLogger
{
	public enum LogMedia
	{
		MSSQL,
		MONGODB,
		TXT,
		EMAIL
	}

	private ILogger MediaLog;

	public GlobalExceptionLogger (LogMedia media) : base()
	{
		switch (media)
		{
			case LogMedia.MSSQL:
				MediaLog = new LoggerMSSQL();
				break;
			case LogMedia.MONGODB:
				MediaLog = new LoggerMongoDB();
				break;
			case LogMedia.TXT:
				MediaLog = new LoggerTXT();
				break;
		}
	}


	public override void Log(ExceptionLoggerContext context)
	{
		//get raw HTTPREQUEST string via @ LogHandler : DelegatingHandler
		var g = context.Request.Properties["test"];

		MediaLog.Log(context.Exception, g.ToString()); 
	}
}


//ILogger.cs
public interface ILogger
{
	void Log(object obj, string message);

}

By: |07/05/2019|categories: