1

I have created a class that inherit for IHttpModule. The class currently fetches the request information and simultaneously log information with that incoming request. I want to modify that request so that when it call my main APi, it should receive the modified request values. Below is the code I am using:

IHttpModule Use

public class KohlsExecutionContextHttpModule1 : IHttpModule
{        
    public void Init(HttpApplication application)
    {
        application.BeginRequest += Application_BeginRequest;            
    }

    #region Private Methods

    private void Application_BeginRequest(object sender, EventArgs e)
    {
        try
        {
            // Tech Note: Initialized the resolver to check for its existence early in this function and exit if doesn't exists.
            var application = sender as HttpApplication;
            if (application == null || application.Context == null || application.Context.Request == null || application.Context.Request.Headers == null) { return; }

            var request = application.Context.Request;
            if (request == null) { return; }

            var bytes = new byte[request.InputStream.Length];
            request.InputStream.Read(bytes, 0, bytes.Length);
            request.InputStream.Position = 0;

            //I need to modify this request content value and pass it on in the pipeline 
            string requestContent = Encoding.UTF8.GetString(bytes);

            var requestHeaders = request.Headers;
            if (requestHeaders == null) { return; }

            var context = request.BuildExecutionContext();

            var addInfo = LogManager.CreateAdditionalInfo("Url", request.Url.ToString(), "Content", requestContent);

            addInfo.Add(_clientSentTimeKey, context.ClientSentTime);
            addInfo.Add(_serviceRequestReceivedTime, context.ReceivedTime.ToDateTimeHighPrecisionUTC());

            HttpContextUtility.LogExecutionMessage("HttpRequest - After Received On Server", addInfo);

            var response = application.Context.Response;

        }
        catch (Exception ex)
        {
            LogManager.LogCritical(ex.Message, ex);
        }
    }
}

In the above code, I am just getting the input request from the string requestContent = Encoding.UTF8.GetString(bytes); code. I wanted to modify this request and send it to the main api which is called after this. Can this be possible.

I am able to achieve it by using the Delegating Handler in web.api where I can modify the request before sending the request to the main caller.

ekad
  • 14,436
  • 26
  • 44
  • 46
Running Rabbit
  • 2,634
  • 15
  • 48
  • 69

0 Answers0