Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

c# - How do I get StatusCode from HttpRequestException?

I'm probably missing something obvious here.

I'm using HttpClient which throws HttpRequestException that contains StatusCode in the Message string.

How can I access that StatusCode?


Edit: More info, I wrote this question in rush.

I'm using HttpClient to access another API within my WebApi project. Yes, I know why I'm calling EnsureSuccessStatusCode(). I want to propagate some errors downstream such as 404 and 403.

All I wanted was to consistently transform HttpRequestException into HttpResponseException using custom ExceptionFilterAttribute.

Unfortunately, HttpRequestException does not carry any extra info I could use besides the message. I was hoping to uncover StatusCode in raw (int or enum) form.

Looks like I can either:

  1. Use the message to switch the status code (bleh)
  2. Or create my version of EnsureSuccessStatusCode and throw exception that's actually usable.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Status code was passed as part of a string to HttpRequestException so that you cannot recover it from such exceptions alone.

The design of System.Net.Http requires you to access HttpResponseMessage.StatusCode instead of waiting for the exception.

http://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage(v=vs.110).aspx

If you are now following the Microsoft guide, make sure you understand clearly why it asks you to call HttpResponseMessage.EnsureSucessStatusCode. If you don't call that function, there should be no exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...