maxkagamine / Moq.Contrib.HttpClient

A set of extension methods for mocking HttpClient and IHttpClientFactory with Moq.
MIT License
188 stars 11 forks source link

Dotnet 7: The value cannot be null or empty. (Parameter 'mediaType') #9

Closed neliason0 closed 2 years ago

neliason0 commented 2 years ago

In dotnet 7 if you do not set the mediaType, and allow the default null value to be used, then an exception will be thrown:

ArgumentException: "The value cannot be null or empty. (Parameter 'mediaType')" at System.Net.Http.Headers.MediaTypeHeaderValue.CheckMediaTypeFormat(String mediaType, String parameterName) at System.Net.Http.StringContent..ctor(String content, Encoding encoding, String mediaType) ...

I looked into this and StringContent has been changed. For the constructor that takes a mediaType string as the third parameter a null value will no longer be translated into the constant DefaultMediaType which is "text/plain". Consequently, when MediaTypeHeaderValue. CheckMediaTypeFormat() is called an ArgumentException will result.

https://github.com/dotnet/runtime/commit/f132942f1a490336cddc06f99abf38226bd9748e

It looks to me like this could be fixed by updating RequestExtension.cs. The various ReturnsResponse methods that have a mediaType parameter with a default of null could change the default to "text/plain". Or the lines of code that directly create a StringContent could use the null-coalescing operator to return "text/plain" when mediaType is null.

maxkagamine commented 2 years ago

Thanks for letting me know! I'll take a look later. I've been wanting to come back to this anyway to add System.Text.Json overloads and maybe clean up the tests/examples a little… would probably be a good idea to have them run on each .NET version, too, to catch this sort of thing.

maxkagamine commented 2 years ago

🚀 Fix deployed in v1.4.0, along with the promised System.Text.Json support