Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How HttpContext RESPONSE END in ASP.NET Core

I want use mvc System.Web.HttpContext.Current.Response.End(); but trying in mvc core 2 with this code:

 private readonly IHttpContextAccessor _httpContextAccessor;

            public SmsService(IUnitOfWork uow ,IHttpContextAccessor httpContextAccessor) 
            {
                _uow = uow;
                _uow.CheckArgumentIsNull(nameof(_uow));
                _LockIPRequest= uow.Set<LockIPRequest>();
                this._httpContextAccessor = httpContextAccessor;
            }

      _httpContextAccessor.HttpContext.Response.WriteAsync("</body></html>");
      _httpContextAccessor.HttpContext.Response.end();

_httpContextAccessor.HttpContext.Response.end();

end(); doesn't work mvc core dont exits

like image 609
amirnowrozian Avatar asked Mar 22 '26 19:03

amirnowrozian


2 Answers

As has been mentioned in the comments, Response.End does not exist in the ASP.NET Core world.

Instead of Response.End, you should set the response status code like so:

 _httpContextAccessor.HttpContext.Response.StatusCode = StatusCodes.Status200OK;

This won't fully "end" the response. The middleware still gets a chance to run, but by setting the status code, the framework has a way to understand that a response has been provided. You will however be responsible for making sure that your downstream middleware does not output other content in response to the request. Although this is often not a problem.

like image 160
RonC Avatar answered Mar 25 '26 08:03

RonC


Now in August 2022, it is possible to call Response.End through the SystemWebAdapters library. I particularly recommend using it only if you are performing a large-scale migration from a .NET Framework project to .NET Core. If you are in a greenfield project, try not to use this library and write your code following the recommendations for ASP.NET Core request/response lifecycle.

like image 42
Gustavo Mauricio De Barros Avatar answered Mar 25 '26 09:03

Gustavo Mauricio De Barros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!