【问题标题】:Getting HTTP Error 400 Calling WCF service via HttpWebRequest获取 HTTP 错误 400 通过 HttpWebRequest 调用 WCF 服务
【发布时间】:2011-03-19 14:26:47
【问题描述】:

我有一个可以通过 jQuery 调用的 WCF 服务,但我无法通过 HttpWebRequest 调用。我之前已经能够使用完全相同的 HttpWebRequest 设置来调用 ASMX 服务,但这是我第一次尝试调用 WCF 服务。我提供了 jQuery 和 C# HttpWebRequest 代码,因此您希望能注意到我做的一些明显错误的事情。

这是我损坏的 C# 代码,最后一行抛出错误 400

string url = "http://www.site.com/Service/Webapi.svc/GetParts";
string parameters = "{part: 'ABCDE'}";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

req.Method = "POST";
req.ContentLength = 0;
req.ContentType = "application/json; charset=utf-8";

if (!string.IsNullOrEmpty(parameters))
{
    byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
    req.ContentLength = byteArray.Length;
    Stream dataStream = req.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
}

HttpWebResponse response = (HttpWebResponse)req.GetResponse();

这是我的工作 jQuery 代码

 $.ajax({
    url: '/Service/Webapi.svc/GetParts',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    data: JSON.stringify({ part: request.term }),
    success: function (data) {
        // Success
    }
});

这是我的相关 web.config 设置

  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="REST">
          <enableWebScript/>
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
    <services>
      <service name="Webapi">
        <endpoint address="" behaviorConfiguration="REST" binding="webHttpBinding" contract="IWebapi"/>
      </service>
    </services>
  </system.serviceModel>

这是我的服务接口,我尝试将“方法”更改为“POST”,但这并没有什么不同。

[ServiceContract]
public interface IWebapi
{
    [OperationContract]
    [WebInvoke(
        Method = "*",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.WrappedRequest)
    ]
    string[] GetParts(string part);
}

这是我的服务实现

public string[] GetParts(string part)
{
    return new string[] {"ABC", "BCD", "CDE"};
}

【问题讨论】:

    标签: c# wcf httpwebrequest


    【解决方案1】:

    好的,这在之前并不明显,但我发现了问题......

    HTTP 错误 400 消息的根本原因是格式无效的 JSON 请求。我在网上找到一篇文章,说如果内容类型错误(不是),就会收到错误 400,所以我决定再次查看 HttpWebRequest 中的所有元素。我发现当通过 jQuery 发送 JSON 请求时,它具有以下格式。

        // Good JSON Formatting
        {"property":"value"}
    

    但在我上面的代码中我使用的是

        // Bad JSON Formatting
        {property:"value"}
    

    进行此更改后,一切正常。为了防止这种情况再次发生,我在 ScottGu 上找到了一篇关于使用 JavaScriptSerializer 构建 ToJSON() 扩展方法的文章。使用这种扩展方法,我想出了以下代码/修复。

    1. 创建了一个请求对象(该属性必须与我正在调用的方法的签名相匹配)

      class Request
      {
          public string part {get; set;}
      }
      
    2. 序列化对象以获得正确的 JSON 格式

      Request request = new Request() { part = "ABC" };
      request.ToJSON();
      

    【讨论】:

      猜你喜欢
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2011-08-25
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多