【问题标题】:Creating a ContentType throws an FormatException创建 ContentType 会引发 FormatException
【发布时间】:2015-02-12 22:09:32
【问题描述】:

我正在使用 ContentType 类来解析网页的内容类型 (type + encoding)。

我注意到此输入失败 (FormatException):

文本/html;字符集:windows-1255

这是代码:

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

为什么会抛出FormatException

【问题讨论】:

    标签: c# mime-types content-type system.net formatexception


    【解决方案1】:
    1. MediaTypeHeaderValue 构造函数只接受媒体类型 ex: 'application/abc',对于任何其他参数,如 CharSet 或任何自定义参数,您可以在此类型上使用 CharSet 和 Parameters 集合。

    或者,您可以从字符串表示创建 MediaTypeHeaderValue,如下所示:

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

    1. WebAPI 附带 3 个默认格式化程序:Json、Xml 和 FormUrlEncoded。 FormUrlEncoded 格式化程序具有与您相同的受支持媒体类型,即 "application/x-www-form-urlencoded" 。注册格式化程序时,您可能会将其添加到格式化程序集合的末尾。现在,当 conneg 过程发生时,它会在格式化程序列表中选择第一个合适的格式化程序来写入响应。在这种情况下,它碰巧选择了我们提供的默认 FormUrlEncoded 格式化程序,而不是您的自定义格式化程序。

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

    【讨论】:

    • 虽然这回答了“不同”的问题,但它确实解决了我的问题:new MediaTypeHeaderValue(..) 只接受 MIME 类型,而 MediateTypeHeaderValue.Parse 接受 Content-Type 值(因此更健壮)。
    【解决方案2】:

    ContentType 构造函数上的 documentation 声明它抛出 FormatException 如果:

    contentType 的格式无法解析。

    在这种情况下,是因为charset:不支持,charset=是:

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

    这种行为是根据W3C specs on content type headers,它声明参数必须遵循这种格式:

    参数:=属性“=”值

    所以等号是attributevalue 之间的记录分隔符。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 1970-01-01
      相关资源
      最近更新 更多