Search code examples
c#async-awaitihttpmodule

HttpModule - Asynchronous not working


I have written an asynchronous HttpModule which logs all the request coming to a website. When the request arrives at the website, the custom http module calls the WebAPI to log the information to the database. .Net 4.5/Visual studio with IIS Express.

////////////Custom HTTP module////////////////////
public class MyHttpLogger : IHttpModule
{
      public void Init(HttpApplication httpApplication)
      {
          EventHandlerTaskAsyncHelper taskAsyncHelper = new EventHandlerTaskAsyncHelper(LogMessage);
          httpApplication.AddOnBeginRequestAsync(taskAsyncHelper.BeginEventHandler, taskAsyncHelper.EndEventHandler);
      }

      private async Task LogMessage(object sender, EventArgs e)
      {
        var app = (HttpApplication)sender;
        var ctx = app.Context;

        //use default credentials aka Windows Credentials
        HttpClientHandler handler = new HttpClientHandler()
        {
            UseDefaultCredentials = true
        };

        using (var client = new HttpClient(handler))
        {
            client.BaseAddress = new Uri("http://localhost:58836/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var actvity = new Activities() { AppId = "TEST123", ActivityId = 10, CreatedBy = 1 };
            await client.PostAsJsonAsync("api/activity", actvity);
        }
    }

Simplified WebAPI code for “api/activity”.

public async Task<HttpResponseMessage>Post(Activities activity)    
{
         await Task.Delay(30000);
         // Database logging code goes here….
        return new HttpResponseMessage(HttpStatusCode.Created);
}

The question is: when the PostAsJsonAsync is getting executed the code stops there. This is correct as the code has to wait. But the calling routine is not getting continued asynchronously as expected and the website response is slower by 30 seconds.

What is wrong with this code? Hooking an async HttpModule should not interfere in the flow of the Http application? Currently when I visit the website the code is getting blocked.


Solution

  • Now, you have to understand the difference between HTTP request and local application. HTTP is totally stateless. Basically you send out a request, the server process it and send back the response. The server does NOT keep any state info about the client, it doesn't have any idea who the client is at all. So in your case, browser sends out a request -> server got it, waited for 30 sec to process it and then sends back result -> browser got the response and this is the point where the browser shows the result. I am assuming what you are trying to do is, browser sends a request, and then you expect the browser to display something and then after 30 sec the server finishes processing and you want to display something else. This is NOT possible to do with await because of the reason mentioned above. What you should do is to write some javascript codes to send out the request with some identifier, and then ask the server every x seconds to see if task{ID} has finished, if so whats the result.