How to change the http status code after starting writing to the HttpContext.Response.Body stream in ASP.NET...












1














I often see that writing to the HttpContext.Response.Body stream is a bad practice (or using PushStreamContent or StreamContent as part of a HttpMessageResponse) cause then you cannot change the HTTP status code if there is something wrong happening.



Is there any workaround to actually perform async writing to the output stream while being able to change HTTP status code in case the operation goes wrong?










share|improve this question



























    1














    I often see that writing to the HttpContext.Response.Body stream is a bad practice (or using PushStreamContent or StreamContent as part of a HttpMessageResponse) cause then you cannot change the HTTP status code if there is something wrong happening.



    Is there any workaround to actually perform async writing to the output stream while being able to change HTTP status code in case the operation goes wrong?










    share|improve this question

























      1












      1








      1







      I often see that writing to the HttpContext.Response.Body stream is a bad practice (or using PushStreamContent or StreamContent as part of a HttpMessageResponse) cause then you cannot change the HTTP status code if there is something wrong happening.



      Is there any workaround to actually perform async writing to the output stream while being able to change HTTP status code in case the operation goes wrong?










      share|improve this question













      I often see that writing to the HttpContext.Response.Body stream is a bad practice (or using PushStreamContent or StreamContent as part of a HttpMessageResponse) cause then you cannot change the HTTP status code if there is something wrong happening.



      Is there any workaround to actually perform async writing to the output stream while being able to change HTTP status code in case the operation goes wrong?







      c# .net .net-core streaming asp.net-core-webapi






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 at 20:08









      Ehouarn Perret

      91211131




      91211131
























          1 Answer
          1






          active

          oldest

          votes


















          2














          Yes. Best practise is write Middleware. For example:



          public class ErrorWrappingMiddleware
          {
          private readonly RequestDelegate next;

          public ErrorWrappingMiddleware(RequestDelegate next)
          {
          this.next = next;
          }

          public async Task Invoke(HttpContext context)
          {
          try
          {
          await next.Invoke(context);
          }
          catch (Exception exception)
          {
          context.Response.StatusCode = 500;
          await context.Response.WriteAsync(...); // change you response body if needed
          }
          }
          }


          and inject them to your pipeline



          public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
          {
          ...
          app.UseMiddleware<ErrorWrappingMiddleware>();
          ...
          }


          And of course you can change your logic in your midleware as you wish, include change Response Code as you wish. Also, you can throw you own exception type, like MyOwnException, catch then in middleware and invoke you own logic wich related to your exception.






          share|improve this answer





















          • thanks that's an interesting solution!
            – Ehouarn Perret
            Nov 11 at 20:48










          • I should have thought about it when reading that part a year ago ^^': docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/… And also to be careful about the order: docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/…
            – Ehouarn Perret
            Nov 11 at 20:55













          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',
          autoActivateHeartbeat: false,
          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%2f53252743%2fhow-to-change-the-http-status-code-after-starting-writing-to-the-httpcontext-res%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









          2














          Yes. Best practise is write Middleware. For example:



          public class ErrorWrappingMiddleware
          {
          private readonly RequestDelegate next;

          public ErrorWrappingMiddleware(RequestDelegate next)
          {
          this.next = next;
          }

          public async Task Invoke(HttpContext context)
          {
          try
          {
          await next.Invoke(context);
          }
          catch (Exception exception)
          {
          context.Response.StatusCode = 500;
          await context.Response.WriteAsync(...); // change you response body if needed
          }
          }
          }


          and inject them to your pipeline



          public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
          {
          ...
          app.UseMiddleware<ErrorWrappingMiddleware>();
          ...
          }


          And of course you can change your logic in your midleware as you wish, include change Response Code as you wish. Also, you can throw you own exception type, like MyOwnException, catch then in middleware and invoke you own logic wich related to your exception.






          share|improve this answer





















          • thanks that's an interesting solution!
            – Ehouarn Perret
            Nov 11 at 20:48










          • I should have thought about it when reading that part a year ago ^^': docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/… And also to be careful about the order: docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/…
            – Ehouarn Perret
            Nov 11 at 20:55


















          2














          Yes. Best practise is write Middleware. For example:



          public class ErrorWrappingMiddleware
          {
          private readonly RequestDelegate next;

          public ErrorWrappingMiddleware(RequestDelegate next)
          {
          this.next = next;
          }

          public async Task Invoke(HttpContext context)
          {
          try
          {
          await next.Invoke(context);
          }
          catch (Exception exception)
          {
          context.Response.StatusCode = 500;
          await context.Response.WriteAsync(...); // change you response body if needed
          }
          }
          }


          and inject them to your pipeline



          public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
          {
          ...
          app.UseMiddleware<ErrorWrappingMiddleware>();
          ...
          }


          And of course you can change your logic in your midleware as you wish, include change Response Code as you wish. Also, you can throw you own exception type, like MyOwnException, catch then in middleware and invoke you own logic wich related to your exception.






          share|improve this answer





















          • thanks that's an interesting solution!
            – Ehouarn Perret
            Nov 11 at 20:48










          • I should have thought about it when reading that part a year ago ^^': docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/… And also to be careful about the order: docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/…
            – Ehouarn Perret
            Nov 11 at 20:55
















          2












          2








          2






          Yes. Best practise is write Middleware. For example:



          public class ErrorWrappingMiddleware
          {
          private readonly RequestDelegate next;

          public ErrorWrappingMiddleware(RequestDelegate next)
          {
          this.next = next;
          }

          public async Task Invoke(HttpContext context)
          {
          try
          {
          await next.Invoke(context);
          }
          catch (Exception exception)
          {
          context.Response.StatusCode = 500;
          await context.Response.WriteAsync(...); // change you response body if needed
          }
          }
          }


          and inject them to your pipeline



          public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
          {
          ...
          app.UseMiddleware<ErrorWrappingMiddleware>();
          ...
          }


          And of course you can change your logic in your midleware as you wish, include change Response Code as you wish. Also, you can throw you own exception type, like MyOwnException, catch then in middleware and invoke you own logic wich related to your exception.






          share|improve this answer












          Yes. Best practise is write Middleware. For example:



          public class ErrorWrappingMiddleware
          {
          private readonly RequestDelegate next;

          public ErrorWrappingMiddleware(RequestDelegate next)
          {
          this.next = next;
          }

          public async Task Invoke(HttpContext context)
          {
          try
          {
          await next.Invoke(context);
          }
          catch (Exception exception)
          {
          context.Response.StatusCode = 500;
          await context.Response.WriteAsync(...); // change you response body if needed
          }
          }
          }


          and inject them to your pipeline



          public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
          {
          ...
          app.UseMiddleware<ErrorWrappingMiddleware>();
          ...
          }


          And of course you can change your logic in your midleware as you wish, include change Response Code as you wish. Also, you can throw you own exception type, like MyOwnException, catch then in middleware and invoke you own logic wich related to your exception.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 at 20:34









          Sergey Shulik

          678824




          678824












          • thanks that's an interesting solution!
            – Ehouarn Perret
            Nov 11 at 20:48










          • I should have thought about it when reading that part a year ago ^^': docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/… And also to be careful about the order: docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/…
            – Ehouarn Perret
            Nov 11 at 20:55




















          • thanks that's an interesting solution!
            – Ehouarn Perret
            Nov 11 at 20:48










          • I should have thought about it when reading that part a year ago ^^': docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/… And also to be careful about the order: docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/…
            – Ehouarn Perret
            Nov 11 at 20:55


















          thanks that's an interesting solution!
          – Ehouarn Perret
          Nov 11 at 20:48




          thanks that's an interesting solution!
          – Ehouarn Perret
          Nov 11 at 20:48












          I should have thought about it when reading that part a year ago ^^': docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/… And also to be careful about the order: docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/…
          – Ehouarn Perret
          Nov 11 at 20:55






          I should have thought about it when reading that part a year ago ^^': docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/… And also to be careful about the order: docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/…
          – Ehouarn Perret
          Nov 11 at 20:55




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53252743%2fhow-to-change-the-http-status-code-after-starting-writing-to-the-httpcontext-res%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

          Full-time equivalent

          さくらももこ

          13 indicted, 8 arrested in Calif. drug cartel investigation