From 77caaf8c72bced85116fabdcec537e4aa8e59bb9 Mon Sep 17 00:00:00 2001 From: Bob Thomas Date: Fri, 27 Apr 2018 09:01:48 -0400 Subject: [PATCH] Cast a null MediaRange reference to a null string When trying to compare a null MediaRange to a string, the implicit cast to string was throwing a NullReferenceException. Fix the operator so that a null MediaRange is cast to a null string. --- src/Nancy/Responses/Negotiation/MediaRange.cs | 5 +++++ .../Responses/Negotiation/MediaRangeFixture.cs | 15 ++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/Nancy/Responses/Negotiation/MediaRange.cs b/src/Nancy/Responses/Negotiation/MediaRange.cs index f8cdf3950a..893585b457 100644 --- a/src/Nancy/Responses/Negotiation/MediaRange.cs +++ b/src/Nancy/Responses/Negotiation/MediaRange.cs @@ -122,6 +122,11 @@ public bool MatchesWithParameters(MediaRange other) /// public static implicit operator string(MediaRange mediaRange) { + if (null == mediaRange) + { + return null; + } + if (mediaRange.Parameters.Any()) { return string.Concat(mediaRange.Type, "/", mediaRange.Subtype, ";", mediaRange.Parameters); diff --git a/test/Nancy.Tests/Unit/Responses/Negotiation/MediaRangeFixture.cs b/test/Nancy.Tests/Unit/Responses/Negotiation/MediaRangeFixture.cs index 208ce846f9..23dba98d85 100644 --- a/test/Nancy.Tests/Unit/Responses/Negotiation/MediaRangeFixture.cs +++ b/test/Nancy.Tests/Unit/Responses/Negotiation/MediaRangeFixture.cs @@ -83,5 +83,18 @@ public void Should_strip_whitespace_when_calling_tostring() // Then range.ToString().ShouldEqual("application/vnd.nancy;a=1;b=2"); } + + [Fact] + public void Should_cast_to_null_string() + { + // Given + MediaRange range = null; + + // When + string cast = (string)range; + + // Then + Assert.Null(cast); + } } -} \ No newline at end of file +}