Wednesday, November 23, 2016

HTTP Call - Differentiate Request and Response with some id

On most cases, user expect last requested service call results to be displayed in UI when multiple service call are made (For Ex: Search textbox to search something will make multiple calls).

We can achieve this with HTTP headers, Let us see the implementation,

First on MVC side we can check custom header present in request or not and then return that header back to response

public class SomeCustomFilter : ActionFilterAttribute
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            if (actionExecutedContext.Request.Headers.Contains("Custom-Request-Id"))
                string HttpRequestID = actionExecutedContext.Request.Headers.GetValues("Custom-Request-Id ").FirstOrDefault();
                actionExecutedContext.Response.Headers.Add("Custom-Request-Id ", HttpRequestID);



Register this filter in global.asax

GlobalConfiguration.Configuration.Filters.Add(new SomeCustomFilter());

Now we are ready at service side, to get request header and return the same value as response header

Next send some header and receive at client side, lets take AngularJS $http for sample

var customRequestId = 0;

    function SomeMethod(url, data) {
        //Increase that request id on each service call, to make it unique
        customRequestId += ;
        var customHeaders = {‘
            Custom - Request - Id’: customRequestId

        method: 'POST',
        url: url,
        headers: customHeaders,
        data: data
            function(data) {
                //check if response and request are matches with latest service call
                var currentRequestId = parseInt(data.headers("Custom-Request-Id"));
                if (customRequestId === currentRequestId) {
                    //your logic goes here…

            function(errorData, status, headers, config) {});

Thats it, now your service call is get latest values to display in UI.

No comments:

Post a Comment