'what's the benefits to use Feature in HttpContext, HttpResponse or HttpResquest

I'm new to asp.net core, struggling with understanding on Feature in HttpContext. If we take a look at DefaultHttpResponse https://source.dot.net/#Microsoft.AspNetCore.Http/Internal/DefaultHttpResponse.cs,c75ed1a6ce866bb3

internal sealed class DefaultHttpResponse : HttpResponse {     
   // ...
   public override int StatusCode {
      get { return HttpResponseFeature.StatusCode; }
      set { HttpResponseFeature.StatusCode = value; }
   }

   public override IHeaderDictionary Headers {
      get { return HttpResponseFeature.Headers; }
   }
}

I don't understand why we need to use HttpResponseFeature here, can't we just define DefaultHttpResponse as:

internal sealed class DefaultHttpResponse : HttpResponse {     
   // ...
   public int StatusCode { get; set; } 
   
   public IHeaderDictionary Headers { get; set; }
}

Then each middleware can still modify DefaultHttpResponse directly?



Solution 1:[1]

As far as I see, they was reasonable.

Starting with internal sealed class DefaultHttpResponse: the internal sealed tell us this class cannot be inheritance. and the DefaultHttpResponse tell us this is the default response. (Which should be treat as some kind of constant, I know the value of it's property changed for each request).

So, if it's intended as constant, better set the status and headers the way it cannot be modified the wrong way easily, so HttpResponseFeature came into play, which contain the response for each request and can only be modified here (turns out that HttpResponseFeature play as single source of trust role).

So, hand-in-hand make it a team.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gordon Khanh Ng.