How to wrap graphql.net endpoint response using asp.net core 2 middleware?









up vote
0
down vote

favorite












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 APIResultAuthorized = false, UserMessage = Constants.Unauthorized, Locale = new Locale(_commonService.GetLanguageFromLocale(locale));
newResponse = request.CreateResponse(HttpStatusCode.Unauthorized, unAuthorisedResult);
var jsonSerializerSettings = new JsonSerializerSettingsContractResolver = 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?










share|improve this question

























    up vote
    0
    down vote

    favorite












    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 APIResultAuthorized = false, UserMessage = Constants.Unauthorized, Locale = new Locale(_commonService.GetLanguageFromLocale(locale));
    newResponse = request.CreateResponse(HttpStatusCode.Unauthorized, unAuthorisedResult);
    var jsonSerializerSettings = new JsonSerializerSettingsContractResolver = 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?










    share|improve this question























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      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 APIResultAuthorized = false, UserMessage = Constants.Unauthorized, Locale = new Locale(_commonService.GetLanguageFromLocale(locale));
      newResponse = request.CreateResponse(HttpStatusCode.Unauthorized, unAuthorisedResult);
      var jsonSerializerSettings = new JsonSerializerSettingsContractResolver = 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?










      share|improve this question













      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 APIResultAuthorized = false, UserMessage = Constants.Unauthorized, Locale = new Locale(_commonService.GetLanguageFromLocale(locale));
      newResponse = request.CreateResponse(HttpStatusCode.Unauthorized, unAuthorisedResult);
      var jsonSerializerSettings = new JsonSerializerSettingsContractResolver = 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?







      c# json asp.net-web-api2 asp.net-core-2.0






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 8 at 19:00









      santosh kumar patro

      1,77282654




      1,77282654






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          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?






          share|improve this answer




















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53214456%2fhow-to-wrap-graphql-net-endpoint-response-using-asp-net-core-2-middleware%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            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?






            share|improve this answer
























              up vote
              0
              down vote













              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?






              share|improve this answer






















                up vote
                0
                down vote










                up vote
                0
                down vote









                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?






                share|improve this answer












                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?







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 9 at 6:11









                Nan Yu

                5,7402646




                5,7402646



























                     

                    draft saved


                    draft discarded















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53214456%2fhow-to-wrap-graphql-net-endpoint-response-using-asp-net-core-2-middleware%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

                    Edmonton

                    Crossroads (UK TV series)