0

I have REST API developed using asp.net web api2. I am migrating the REST API to GraphQL.net endpoints using asp.net core 2. In the existing REST API code I have a Delegating handler used to extend the result of REST API call with additional data which in this case is add localization data to the response.Since Delegating handler are no more supported in asp.net core 2. I am trying to migrate the existing Delegating handler to Middleware component.

For reference purpose I followed the details mentioned at : Extending WebApi response using OWIN Middleware and https://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information

Here I have couple of queries:

  1. How to map the below code in case of Middlware ? var response = await base.SendAsync(request, cancellationToken);

  2. Where should I place the middleware in Startup.cs Configure method.

  3. Middleware equivalent of the existing Delegating Handler

Code:

public class CommonResponserHandler : DelegatingHandler
{
    ICommonService _commonService = new CommonService();
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        string locale = string.Empty;
        if (request.Headers.Contains("Accept-Language"))
        {
            locale = request.Headers.GetValues("Accept-Language").First();
        }

        bool initialAuthorizationStatus = GetInitialAuthorization(request);
        var response = await base.SendAsync(request, cancellationToken);
        APIResult commonResponse;
        if (response.TryGetContentValue<APIResult>(out commonResponse))
        {
            //populate common response here;
            UpdateCommonResponse(request, response, commonResponse);
            //UpdateCommonResponse(basicResponse, commonResponse);
            HttpResponseMessage newResponse;
            bool authorizatinCheckResult = AssertAuthorization(initialAuthorizationStatus, request);
            if (authorizatinCheckResult)
            {
                newResponse = request.CreateResponse(response.StatusCode, commonResponse);
            }
            else
            {
                var unAuthorisedResult = new APIResult{Authorized = false, UserMessage = Constants.Unauthorized, Locale = new Locale(_commonService.GetLanguageFromLocale(locale))};
                newResponse = request.CreateResponse(HttpStatusCode.Unauthorized, unAuthorisedResult);
                var jsonSerializerSettings = new JsonSerializerSettings{ContractResolver = new CamelCasePropertyNamesContractResolver()};
                HttpContext.Current.Items["401message"] = JsonConvert.SerializeObject(unAuthorisedResult, Formatting.Indented, jsonSerializerSettings);
            }

            //Add headers from old response to new response
            foreach (var header in response.Headers)
            {
                newResponse.Headers.Add(header.Key, header.Value);
            }

            return newResponse;
        }

        return response;
    }
}

Can anyone help me to provide their guidance in resolving the issue?

santosh kumar patro
  • 5,491
  • 12
  • 48
  • 105

1 Answers1

0

Please read the ASP.NET Core Middleware documentation for a better understanding on how middlewares work.

The middleware takes in the next RequestDelegate in its constructor and supports an Invoke method .For example :

 public class CommonResponserMiddleware
{
    private readonly RequestDelegate _next;

    public CommonResponserMiddleware(RequestDelegate next)
    {
        _next = next;

    }

    public async Task Invoke(HttpContext context)
    {
        //process context.Request

        await _next.Invoke(context);

        //process context.Response

    }
}

public static class CommonResponserExtensions
{
    public static IApplicationBuilder UseCommonResponser(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CommonResponserMiddleware>();
    }
}

And use in Starup.cs:

public void Configure(IApplicationBuilder app) {
    //...other configuration

    app.UseCommonResponser();

    //...other configuration
}

You can also refer to related SO question:

Registering a new DelegatingHandler in ASP.NET Core Web API

How can I wrap Web API responses(in .net core) for consistency?

Nan Yu
  • 21,285
  • 5
  • 39
  • 110