Fix NullReferenceException in ConfigurableResponseNegotiator when Accept-Charset header is absent#3
Conversation
…on AcceptCharset.Count Co-authored-by: gimlichael <8550919+gimlichael@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
Fixes a NullReferenceException in ConfigurableResponseNegotiator.GetEncoding when a request does not include an Accept-Charset header, so the negotiator falls back to the default encoding as intended.
Changes:
- Updated the
Accept-Charsetcount check inGetEncodingto be null-aware.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| { | ||
| var acceptCharset = request.GetTypedHeaders().AcceptCharset; | ||
| if (acceptCharset.Count > 0) | ||
| if (acceptCharset?.Count > 0) |
There was a problem hiding this comment.
acceptCharset?.Count > 0 produces a nullable boolean (because ?.Count is int?), which cannot be used directly as an if condition. This will fail to compile. Use a non-nullable condition (e.g., coalesce the count to 0, compare to true, or use a property pattern like checking acceptCharset is { Count: > 0 }).
| if (acceptCharset?.Count > 0) | |
| if (acceptCharset is { Count: > 0 }) |
| var acceptCharset = request.GetTypedHeaders().AcceptCharset; | ||
| if (acceptCharset.Count > 0) | ||
| if (acceptCharset?.Count > 0) |
There was a problem hiding this comment.
Consider adding a unit test for the reported scenario (no Accept-Charset header) to ensure GetEncoding returns the default encoding and does not throw. There are already GetEncoding_* tests in the test project, but none cover the missing-header case.
GetTypedHeaders().AcceptCharsetreturnsnullwhen noAccept-Charsetheader is present in the request, causing aNullReferenceExceptionon.Count.Change
Applied null-conditional operator in
ConfigurableResponseNegotiator.GetEncoding:When
AcceptCharsetisnull,?.Countyieldsnull, the condition evaluates tofalse, and the method falls through toGetDefaultEncoding()as intended.💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.