I'm trying to check if an Accept
header includes a MIME type like this:
public static bool AcceptsView(this HttpRequest request) => request.Headers.Accept.Contains("text/html");
However even when the Accept header is Accept: text/html, text/plain, application/json
it returns false
. What am I doing wrong?
Best Answer
The
Microsoft.AspNetCore.Http.HttpRequest
defines a property calledHeaders
which is anIHeaderDictionary
. This interface defines anAccept
property which is aStringValues
. This type basically a string collection which implements a lots of interfaces, likeIEnumerable<string>
.Whenever you call
Contains
on theAccept
that checks whether the provided string is present in the collection. In your case this property contains a single element. Not one element per acceptable mime type.So, you have a collection with a single element
text/html, text/plain, application/json
and you are checking whether it has an element withtext/html
. That's the reason why it always returns false.Option 1
So, you should check whether is there any item inside the
StringValues
collection which contains the provided string:Option 2
Another way to perform this check is to use the
GetTypedHeaders
. This will return aRequestHeaders
instance. Its Accept property is not aStringValues
rather aIList<MediaTypeHeaderValue>
. So, here you have oneMediaTypeHeaderValue
per acceptable mime type.The
MediaTypeHeaderValue
has a property calledMediaType
. Its type is aStringSegment
which does have aValue
property.You can also avoid hard coding
text/html
. TheSystem.Net.Mime
namespaces defines several classes likeMediaTypeNames
orMediaTypeNames.Text
. The latter one has a constant calledHtml
which contains thetext/html