问题
I'm a bit confused by the name of this function.
Why isn't it just TryAdd
? What is it that it doesn't validate? If I use this function, can it still throw in some cases? Can I somehow "try to add" without getting any exceptions and only false returned if it fails?
EDIT:
I think the 2 questions are opposing each other. If I call with TryAddWithoutValidation
does it actually add the invalid headers or it just returns false if they are invalid?
回答1:
The HttpHeaders.TryAddWithoutValidation returns false if the key is null/empty OR it's in the list of invalid headers.
The Add method, besides throwing exceptions instead of returning false, calls the method ParseAndAddValue. Internally it gets a parser for each key you try to add and only accepts the value if the parse is successfull (checking if the key you're trying to add is valid for that kind of request, for example).
回答2:
HttpRequestMessage
and HttpResponseMessage
do not accept Content
related headers, by convention, you are supposed to add Content
related headers into HttpContent
.
So if you call
response.Headers.Add("Content-Type", ...);
response.Headers.Add("Content-Length",...);
you will get an exception.
But you still don't want to follow HttpClient
's convention and you may need this while you are proxying some requests. Then you can call.
response.Headers.TryAddWithoutValidation("Content-Type", ...);
response.Headers.TryAddWithoutValidation("Content-Length",...);
This will add headers and it will send/receive headers without validating.
来源:https://stackoverflow.com/questions/42022364/does-httpheaders-tryaddwithoutvalidation-validate-or-not