C#, HTTPClient - IfMatch format requirements?

无人久伴 提交于 2020-01-04 05:57:05

问题


I am using the System.Net.Http.HttpClient found in .Net 4.5 in conjunction with CouchDb.

I have a revision of a document being: 3-789d4d2b33bf4505f8f23fd4a1025a4e.

The issue is that I can't get that to work with the If-Match header flag on the request.

var req = new HttpRequestMessage(HttpMethod.Delete, url);
req.Headers.IfMatch.Add(
    new EntityTagHeaderValue("3-789d4d2b33bf4505f8f23fd4a1025a4e"));

The EntityTagHeaderValue causes a format exception:

"The format of value '3-789d4d2b33bf4505f8f23fd4a1025a4e' is invalid."

I have tried to add it using pure strings via: req.Headers.Add(string, string), still no luck.

The working solution I have found is:

req.Headers.TryAddWithoutValidation("If-Match", rev);

The question is, what are the requirements on a If-Match header?


回答1:


The tag is required to be an entity-tag as defined in section 3.11 of the HTTP specification, which in turn defines it as a quoted-string (see section 2.2 of the HTTP specification), optionally preceded by W/ to indicate a 'weak' tag. Roughly speaking, this means it can be pretty much any text at all but it has to be enclosed in double quotes. (If present, the W/ prefix comes before the opening quote.) The text within quotes can be anything except control characters or ". (And a " is allowed to appear if preceded by a \).

If an HTTP server reports an ETag as 3-789d4d2b33bf4505f8f23fd4a1025a4e then it's violating the spec. It should really be something like "3-789d4d2b33bf4505f8f23fd4a1025a4e".

That said, it seems to be quite common for entity tags to be missing the quotes. Apparently HttpClient is slightly unusual in enforcing the rules, making it slightly cumbersome if you're having to deal with a server that breaks the rules.

Note that there's a bug in the spec. The published HTTP 1.1 spec allows quoted strings to end in a backslash, e.g., "foo\" or even just "\". However, this was not the intention. The intention was that a backslash would always be followed by another character, and that the closing quote would be distinguished by not being preceded by a \, something those last two examples violate. See this bug report. It has been fixed in the current draft of the next version of the HTTP 1.1 spec (HTTP bis, which, as seems to be the way with web standards, is due to be published any decade now). So although those two strings are technically legal today, implementors would be wise to avoid that sort of thing.



来源:https://stackoverflow.com/questions/15906198/c-httpclient-ifmatch-format-requirements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!