如何使用带有ContentType ="application/json"的HttpWebRequest GET方法; [英] How do I use HttpWebRequest GET method w/ ContentType="application/json"

查看:723
本文介绍了如何使用带有ContentType ="application/json"的HttpWebRequest GET方法;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真的很简单,运行此Silverlight4示例,并注释掉ContentType属性,您将从XML的服务中获取响应.现在取消注释该属性并运行它,您将获得一个ProtocolViolationException,应该发生的情况是该服务返回JSON格式的数据.

This one is real simple, run this Silverlight4 example with the ContentType property commented out and you'll get back a response from from my service in xml. Now uncomment the property and run it and you'll get an ProtocolViolationException, what should happen is the service returns JSON formatted data.

#if DEBUG
                Address = "http://localhost.:55437/Services/GetFoodDescriptionsLookup(2100)";
#else
                Address = "http://stephenpattenconsulting.com/Services/GetFoodDescriptionsLookup(2100)";
#endif

Uri httpSite = new Uri(Address);

HttpWebRequest wreq = 
(HttpWebRequest)WebRequestCreator.ClientHttp.Create(httpSite);

//wreq.ContentType = "application/json"; // Wrong
wreq.Accept = "application/json"; // Right

wreq.BeginGetResponse((cb) =>
{
    HttpWebRequest rq = cb.AsyncState as HttpWebRequest;
    HttpWebResponse resp = rq.EndGetResponse(cb) as HttpWebResponse; // Exception
    StreamReader rdr = new StreamReader(resp.GetResponseStream());
    string result =  rdr.ReadToEnd(); 
    rdr.Close();
}, wreq);

新异常

System.NotSupportedException未由用户代码处理 留言=" 堆栈跟踪: 在System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod,对象状态) 在System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 在com.patten.silverlight.ViewModels.WebRequestLiteViewModel.b_ 0(IAsyncResult cb) 在System.Net.Browser.BrowserHttpWebRequest中.<> c _DisplayClassd.b__b(对象state2) 在System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(对象状态) 在System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔ignoreSyncCtx) 在System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() 在System.Threading.ThreadPoolWorkQueue.Dispatch() 在System.Threading. ThreadPoolWaitCallback.PerformWaitCallback() InnerException:System.NotSupportedException Message =不支持指定的方法. 堆栈跟踪: 在System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) 在System.Net.Browser.BrowserHttpWebRequest处.<> c _DisplayClass5.b_ 4(对象sendState) 在System.Net.Browser.AsyncHelper中.<> c _DisplayClass2.b__0(对象sendState) InnerException:

System.NotSupportedException was unhandled by user code Message="" StackTrace: at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at com.patten.silverlight.ViewModels.WebRequestLiteViewModel.b_0(IAsyncResult cb) at System.Net.Browser.BrowserHttpWebRequest.<>c_DisplayClassd.b__b(Object state2) at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading.ThreadPoolWaitCallback.PerformWaitCallback() InnerException: System.NotSupportedException Message=Specified method is not supported. StackTrace: at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.BrowserHttpWebRequest.<>c_DisplayClass5.b_4(Object sendState) at System.Net.Browser.AsyncHelper.<>c_DisplayClass2.b__0(Object sendState) InnerException:

正在工作

我遇到的异常是由于黑客入侵,我使用它来使Fiddler显示回送适配器,即

The exception that I was getting was due to a hack I use to get Fiddler to show the loop-back adapter i.e. http://localhost.:55437/Services/GetFoodDescriptionsLookup(2100), notice the extra DOT after the word localhost.

就是这样!

我知道每个人都在想什么,如果我本可以包括其中的一些细节,就可以解决..例如,更改URI的debug标志,我删除了大部分代码,以便于在SO上阅读,认为问题出在网络堆栈中.辛苦的教训.

I know what everyone is thinking, this could have been solved it I would have included some of these details.. like the debug flag that changes the URI, I removed most of the code to make it easier to read on SO, thinking that the problem was in the networking stack. Hard lesson(s) learned.

感谢所有花时间参与此工作的人,无论是在stackoverflow上还是在离线状态下.

Thanks to everyone who took the time to get involved with this, both on stackoverflow and offline.

为了完整起见,我添加了jQuery函数,这使我一直想在SL4应用程序中设置内容类型"而不是接受". (阅读DOCS!)

For completeness I have added the jQuery function that had me thinking this whole time I needed to be setting "content-type" instead of "accept" when in the SL4 application. (READ THE DOCS!)

function CallService(serviceUrl, data, callback) {
    $.ajax({
        url: serviceUrl,
        data: data,
        dataType: 'json',
        contextType: "application/json", 
        cache: false,
        success: callback,
        error: function (msg) {
            alert("Request Failed!");
        }
    });
}

推荐答案

Stephen,将内容类型设置为允许SENDING JSON,但不接收它.有几种方法可以做到这一点.您可以同时支持JSON和XML或仅支持JSON.如果您只想支持JSON,则可以通过在WebGet属性上为服务操作设置ResponseFormat属性来实现.

Stephen, setting the content type is to allow SENDING JSON, not receiving it. There are several ways to do this. You can support both JSON and XML or only JSON. If all you want to do is support JSON then you can do this by setting the ResponseFormat property on the WebGet attribute for the service operation.

如果要同时支持JSON和XML,则需要在服务上启用自动格式选择并发送"application/json"的接受标头,否则, 可以在查询字符串中使用格式字符串参数,并使服务使用WebOperationContext.OutgoingResponse.Format属性.

If you want to support both JSON and XML then you need to either enable automatic format selection on the service and send an accept header of "application/json", otherwise you can use a format string parameter in the query string and have the service use the WebOperationContext.OutgoingResponse.Format property.

这是

Here's a post that covers various ways to do this from the server side. If you go the route of supporting automatic format selection then you need to set the accept header of the HttpWebRequest to "application/json"

这篇关于如何使用带有ContentType ="application/json"的HttpWebRequest GET方法;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆