dotnet / dotnet/aspnetcore

Avoid NRE in HttpContext debugger display with empty feature collection

Open
#52,756 3 comments 1 reaction 1 assignee Claimed by @Kahbazi View on GitHub
area-networking
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

HttpContext and friends output friendly debug text in .NET 8, such as the request's URL and response's status code. However, it is possible to create an "empty" HttpContext with `var context = new DefaultHttpContext(new FeatureCollection());`.

An empty HttpContext will throw a NRE when accessing many properties, e.g. `HttpResponse.StatusCode`. This results in the debug display being `Object reference not set to an instance of an object.`.

### Expected Behavior

Couple of options:
1. Get values from `HttpContext` using feature collection. If the feature is null, e.g. `IHttpResponseFeature`, then skip writing its information.
2. Put a try/catch around debug text generation. If an error occurs then fallback to outputting the type name.

### Steps To Reproduce

```cs
var context = new DefaultHttpContext(new FeatureCollection());
// view context in the debugger
```

### Exceptions (if any)

_No response_

### .NET Version

net9.0

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.