Как установить заголовки с помощью Silverlight GET HttpWebRequest?

StackOverflow https://stackoverflow.com/questions/622897

Вопрос

Выполнение запроса к службе RESTful в Silverlight с помощью HttpWebRequest работает хорошо, если я не добавляю заголовки в запрос.

Как только я добавлю заголовок, используя такой код

var webReq = (HttpWebRequest)WebRequest.Create(new Uri(_RemoteAddress, "GetProviderMetadata"));
webReq.Method = HttpMethodType.Get;
webReq.Headers["SomeToken"] = "someTokenValue";

Исключение вставляется внизу этого вопроса, как только вызывается EndGetResponse () . Кто-нибудь знает, почему это? Добавление заголовков для получения запросов, кажется, работает нормально в нормальном .NET, так что я предполагаю, что это какое-то ограничение Silverlight, но я не могу найти какую-либо документацию, которая разъясняет.

   {System.NotSupportedException ---> System.NotSupportedException: Specified method is not supported.
  at System.Net.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
  at System.Net.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
  at System.Net.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)
  --- End of inner exception stack trace ---
  at System.Net.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
  at System.Net.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
  at System.Net.BrowserHttpWebRequest.<>c__DisplayClassd.<InvokeGetResponseCallback>b__b(Object state2)
  at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)}
   [System.NotSupportedException]: {System.NotSupportedException ---> System.NotSupportedException: Specified method is not supported.
  at System.Net.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
  at System.Net.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
  at System.Net.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)
  --- End of inner exception stack trace ---
  at System.Net.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
  at System.Net.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
  at System.Net.BrowserHttpWebRequest.<>c__DisplayClassd.<InvokeGetResponseCallback>b__b(Object state2)
  at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)}
   _className: "System.NotSupportedException"
   _data: {System.Collections.ListDictionaryInternal}
   _dynamicMethods: null
   _exceptionMethod: null
   _exceptionMethodString: null
   _helpURL: null
   _HResult: -2146233067
   _innerException: {System.NotSupportedException: Specified method is not supported.
  at System.Net.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
  at System.Net.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
  at System.Net.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)}
   _message: ""
   _remoteStackIndex: 0
   _remoteStackTraceString: null
   _source: "System.Windows"
   _stackTrace: {sbyte[192]}
   _stackTraceString: null
   _xcode: -532462766
   _xptrs: 0
   Data: {System.Collections.ListDictionaryInternal}
   HelpLink: null
   HResult: -2146233067
   InnerException: {System.NotSupportedException: Specified method is not supported.
  at System.Net.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
  at System.Net.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
  at System.Net.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)}
   Message: ""
   Source: "System.Windows"
   StackTrace: "   at System.Net.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)\r\n   at System.Net.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n   at Intellidimension.RdfEntity.Service.RemoteEntityServiceProviderClient.getProviderMetadataResponse(IAsyncResult result)\r\n   at System.Net.BrowserHttpWebRequest.<>c__DisplayClassd.<InvokeGetResponseCallback>b__b(Object state2)\r\n   at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)\r\n   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)\r\n   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)\r\n   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)"
   System.Runtime.InteropServices._Exception.HelpLink: null
   System.Runtime.InteropServices._Exception.Source: "System.Windows"
Это было полезно?

Решение

Silverlight поддерживает настройку заголовков только с помощью метода POST, а не метода GET. Это связано с ограничением реализации стека TCP / IP в Silverlight. Он использует API расширения браузера вместо того, чтобы идти прямо против API хост-системы.

Другие советы

Укажите " Клиентский HTTP " обработка перед тем, как позвонить, инициируйте свой веб-запрос.

Вот так:

bool httpResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
bool httpsResult = WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top