WCF POST方法获取错误400错误请求

时间:2016-10-23 04:44:45

标签: c# wcf

我正在使用WCF POST方法,一旦我向服务添加参数POST,其返回错误400 Bad Request,如果我将参数留空,则可以访问我的服务。

这是我的界面:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.IO;
namespace SampleArticle
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IRestService" in both code and config file together.
    [ServiceContract(Namespace="IRestService/JSONData")]
    public interface IRestService
    {

        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped,UriTemplate = "authorize")]
        Stream authorize(Stream streamdata);

    }
}

这是我的Web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <appSettings>

    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />

  </system.web>

  <system.serviceModel>


    <services>
      <service name="SampleArticle.RestService" behaviorConfiguration="serviceBehavior">
        <endpoint address="" binding="webHttpBinding" contract="SampleArticle.IRestService" behaviorConfiguration="web"></endpoint>        
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>

        <behavior name="serviceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>

      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="web">
          <webHttp />
        </behavior>
      </endpointBehaviors>

    </behaviors>

    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>


    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>


 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
   <directoryBrowse enabled="true" />

  </system.webServer>

</configuration>

我使用Msxml2.ServerXMLHTTP进行POST

Dim objXmlHttpMain , URL

URL="http://localhost/SampleArticle/RestService.svc/authorize" 

strJSONToSend = "{""acctId"": ""Test10001"","
strJSONToSend = strJSONToSend & """language"": 200,"
strJSONToSend = strJSONToSend & """Code"": ""Test"","
strJSONToSend = strJSONToSend & """token"": ""abcd123412341234"","
strJSONToSend = strJSONToSend & """serialNo"": ""20161020160455982841""}"

// if i set the parameter to empty i can access to the service
'strJSONToSend  = ""
Set objXmlHttpMain = CreateObject("Msxml2.ServerXMLHTTP") 
'on error resume next 
objXmlHttpMain.open "POST",URL, False 

// if i change the  "application/json" to "application/x-www-form-urlencoded" it works 
'objXmlHttpMain.setRequestHeader "Content-Type", "application/json"
objXmlHttpMain.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

objXmlHttpMain.send strJSONToSend 


//check for output
S = objXmlHttpMain.responseText
response.write S

set objJSONDoc = nothing 
set objResult = nothing

服务器日志消息

  

操作的传入消息&#39;授权&#39; (合同&#39; IRestService&#39; with namespace&#39; IRestService / JSONData&#39;)包含无法识别的http正文格式值&#39; Json&#39;。预期的正文格式值是&#39; Raw&#39;。这可能是因为尚未在绑定上配置WebContentTypeMapper。有关更多详细信息,请参阅WebContentTypeMapper的文档。

如果我更改Content-Type&#34; application / json&#34; to&#34; application / x-www-form-urlencoded&#34; 它工作,但我需要JSON格式的数据。 我有什么设置吗?请指教。

1 个答案:

答案 0 :(得分:0)

我已经解决了我的问题,我添加了自定义WebContentTypeMapper。 以下是我的示例编码:

创建新类以允许以RAW类型

接收数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace SampleArticle
{
    public class MyWebContentTypeMapper : WebContentTypeMapper
    {
        public override WebContentFormat GetMessageFormatForContentType(string contentType)
        {

            return WebContentFormat.Raw;
        }
    }
}

Web.Config将自定义绑定添加到服务

<system.serviceModel>
    <services>
        <service name="SampleArticle.RestService" behaviorConfiguration="serviceBehavior">
            <endpoint address="" binding="customBinding" bindingConfiguration="RawReceiveCapable" contract="SampleArticle.IRestService" behaviorConfiguration="web"></endpoint>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="serviceBehavior">
                <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
            <behavior name="">
                <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
        </serviceBehaviors>
        <endpointBehaviors>
            <behavior name="web">
                <webHttp/>
            </behavior>
        </endpointBehaviors>
    </behaviors>


    <bindings>
        <customBinding>
            <binding name="RawReceiveCapable">
                <webMessageEncoding webContentTypeMapperType="SampleArticle.MyWebContentTypeMapper, SampleArticle, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
                <httpTransport manualAddressing="true" maxReceivedMessageSize="524288000" transferMode="Streamed"/>
            </binding>
        </customBinding>
    </bindings>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>

这解决了我的问题,希望对其他人有所帮助。感谢您的帮助