Does HttpHeaders.TryAddWithoutValidation validate or not?

点点圈 提交于 2019-12-10 18:26:38

问题


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

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