在Silverlight中使用HttpWebResponse 獲取Header信息

在Silverlight 3 中使用HttpWebResponse獲取header代碼:

HttpWebResponse response = state as HttpWebResponse;

string para = response.Headers["PARA"];

第二句發生異常:

System.NotImplementedException: 該類沒有實現這一屬性。
   位於 System.Net.WebResponse.get_Headers()
   位於 SilverlightApplication2.MainPage.GetResponse(Object state)


解決:

在應用程序開始時添加以下語句(例如MainClass 的構造函數中)

bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);


解釋如下:

http://blogs.msdn.com/b/carlosfigueira/archive/2009/08/15/fault-support-in-silverlight-3.aspx

When Silverlight 2 was launched, creating SL apps which handled faults thrown by WCF services was at least a little cumbesome. According to the instructions listed at http://msdn.microsoft.com/en-us/library/dd470096(VS.95).aspx, one needed to have a special behavior at the server to change the fault HTTP response status code, which is normally 500 (Internal Server Error) to 200 (OK), to overcome the limitation of the networking stack in which the HTTP response body could only be read in 200 responses. This was cumbersome for a variety of reasons: the behavior didn't apply to all faults (including those related to authentication), an extra piece of data was required at the service side (and if you don't have control of the service this is not an option).

With Silverlight 3, there is now an option to use a different networking stack (the client networking stack), which bypasses the browser HTTP stack and uses the native OS stack directly. By using that stack, the SL app is now able to read the responses to any HTTP request (including those with status code other than 200, like the ones normally used in faults). The full differences between the new (client) and the "old" (browser) stacks are nicely listed at http://blogs.msdn.com/silverlight_sdk/archive/2009/08/12/new-networking-stack-in-silverlight-3.aspx.

So, what does it mean for consuming faults from WCF (or not) services? As long as you have the following line in the beginning of the SL application (e.g., on the constructor for the MainPage class), the app will be using the new stack for all communication to http:// services:

     bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);

If the registration returns true (which it should, unless the prefix has been previously registered), then you now don't need any special behaviors on the WCF service - all faults should be received correcly by the SL application.


參考:

http://stackoverflow.com/questions/1278973/retrieve-response-headers-in-silverlight

http://blogs.msdn.com/carlosfigueira/archive/2009/08/15/fault-support-in-silverlight-3.aspx

http://msdn.microsoft.com/en-us/library/dd470096%28VS.95%29.aspx

http://blogs.msdn.com/silverlight%5Fsdk/archive/2009/08/12/new-networking-stack-in-silverlight-3.aspx



                  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章