带有JSON正文的DotNetOpenAuth POST示例

问题描述

| 我正在使用DotNetopenAuth并尝试将JSON对象发布到服务器。 服务器抛出WebContentType = Raw错误
Authorization: OAuth
oauth_token=\"V9vVXD51ehUU6WmY%2FQ41qta0RfY%3D\",oauth_consumer_key=\"CHiawRiAb299cOas\",oauth_nonce=\"BBTM4csg\",oauth_signature_method=\"HMAC-SHA1\",oauth_signature=\"KZJZvT630f2KenB9l9tqSLI%2FfHA%3D\",oauth_version=\"1.0\",oauth_timestamp=\"1306870331\"
Content-Type: application/x-www-form-urlencoded; charset=utf-8 
User-Agent: DotNetopenAuth/3.4.6.10357
我想我真的在寻找有关如何执行此操作的示例?还是对样本的网址? 我目前正在尝试
WebRequest httpRequest = consumer.
    PrepareAuthorizedRequest(endpoint,Accesstoken,para);
httpRequest.ContentType = \"application/json\";
WebResponse webResponse = httpRequest.GetResponse();
    

解决方法

        最初由iain回答: 好的,我设法解决了这个问题。我发现的问题是我正在从
ConsumerBase
调用
PrepareAuthorizedRequest
。然后,内容类型将不被接受,并且始终标记为“ 4”。为解决此问题,我正常调用了ѭ2,然后创建了一个新的HttpWebRequest并将其复制到OAuth Authorization标头中。
HttpWebRequest httpRequest = consumer.
    PrepareAuthorizedRequest(endpoint,AccessToken);

HttpWebRequest httpWebRequest = (HttpWebRequest)
    WebRequest.Create(serviceBase + \"/Edit/6363241\");

foreach (string headerKey in httpRequest.Headers.AllKeys)
    httpWebRequest.Headers.Add(headerKey,httpRequest.Headers[headerKey]);


httpWebRequest.ContentType = \"application/json\";
httpWebRequest.Method = \"POST\";

using (Stream requestStream = httpWebRequest.GetRequestStream())
{
    byte[] bytes = Encoding.UTF8.GetBytes(test22);
    requestStream.Write(bytes,bytes.Length);
}

WebResponse webResponse = httpWebRequest.GetResponse();

string responseContent = new StreamReader(webResponse.GetResponseStream()).
    ReadToEnd();
    ,        我相信您的错误是您将
para
作为第三个参数传递给
PreparedAuthorizedRequest
。如果要传递extraParameters,则是告诉DotNetOpenAuth这些附加参数必须包含在消息有效负载中,这需要特定的内容类型。如果您仅将“ 9”作为第三个参数传递,我认为您可以避免所有这些标头复制并使用您自己的自定义内容类型。     ,        获取请求流之前,您需要通过
httpRequest.ContentLength
属性设置
Content-Length
头。 另外,虽然您已经拥有了它,但我搜索了数小时试图找出我所缺少的东西,即
endpoint
声明中的
HttpDeliveryMethods.AuthorizationHeaderRequest
string url = serviceBase + \"/Booking/6363241\";
HttpDeliveryMethods methods = HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest;
MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint(url,methods);
WebRequest httpRequest = consumer.PrepareAuthorizedRequest(endpoint,AccessToken);
httpRequest.ContentType = \"application/json\";

byte[] bytes = Encoding.UTF8.GetBytes(test22);
httpRequest.ContentLength = bytes.Length;

using (Stream requestStream = httpRequest.GetRequestStream())
{
    requestStream.Write(bytes,bytes.Length);
}

string responseContent;
using (HttpWebResposne response = (HttpWebResponse)httpRequest.GetResponseStream())
using (StreamReader reader = new StreamReader(response))
{
    responseContent = reader.ReadToEnd();
}