No1Lives4Ever
No1Lives4Ever

Reputation: 6883

Creating a ContentType throws an FormatException

I'm working with ContentType class to parse content type (type + encoding) of a webpage.

I'm noticed that this input fails (FormatException):

text/html; charset: windows-1255

This is the code:

using System.Net.Mime;
//...
ContentType ct;
try
{
    ct = new ContentType(content_type);
}
catch (FormatException ex)
{
    return eFileType.Unknown;
}

Why it's throwing FormatException?

Upvotes: 1

Views: 946

Answers (2)

Shankar S
Shankar S

Reputation: 405

  1. MediaTypeHeaderValue constructor expects to take in only the media type ex: 'application/abc', for any other parameters like CharSet or any custom ones, you can use the CharSet and Parameters collection on this type.

Alternatively, you can create a MediaTypeHeaderValue from a string represenation like below:

MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded; charset=utf-8")

  1. WebAPI ships with 3 default formatters : Json, Xml and FormUrlEncoded. The FormUrlEncoded formatter has the same supported media type as yours i.e "application/x-www-form-urlencoded" . When you register your formatter, you are probably adding it to the end of the formatter collection. Now when the conneg process happens, it picks up the 1st suitable formatter in the list of formatters to write the response. In this case it happens to pick the default FormUrlEncoded formatter that we ship instead of your custom formatter.

https://forums.asp.net/t/1780855.aspx?Media+type+name+and+a+custom+formatter+

Upvotes: 4

Patrick Hofman
Patrick Hofman

Reputation: 156948

The documentation on the ContentType constructor states that it throws an FormatException if:

contentType is in a form that cannot be parsed.

In this case, it is because charset: is not supported, charset= is:

var x = new ContentType("text/html; charset=windows-1255");

This behavior is according to the W3C specs on content type headers, that states that a parameter must follow this format:

parameter := attribute "=" value

So an equals sign is the documented separator between attribute and value.

Upvotes: 4

Related Questions