WCF POST方法得到错误400错误请求

本文关键字:错误 请求 POST 方法 WCF | 更新日期: 2023-09-27 18:14:30

我使用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);
    }
}

This is my 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

服务器日志信息

操作'授权'(合同'IRestService'与命名空间'IRestService/JSONData')的传入消息包含一个无法识别的http主体格式值'Json'。预期的主体格式值是'Raw'。这可能是因为没有在绑定上配置WebContentTypeMapper。查看WebContentTypeMapper的文档了解更多细节。

如果我将Content-Type "application/json"更改为"application/x-www-form-urlencoded"它的工作原理,但我需要JSON格式的数据。有我遗漏的设置吗?请建议。

WCF POST方法得到错误400错误请求

我已经解决了我的问题,我添加了自定义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;
        }
    }
}

网络。配置添加自定义绑定到服务

<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>

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