簡體   English   中英

WCF POST方法獲取錯誤400錯誤請求

[英]WCF POST method get error 400 Bad Request

我正在使用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

服務器日志消息

操作“授權”(帶有名稱空間“ IRestService / JSONData”的合同“ IRestService”)的傳入消息包含無法識別的http正文格式值“ Json”。 預期的正文格式值為“ Raw”。 這可能是因為尚未在綁定上配置WebContentTypeMapper。 有關更多詳細信息,請參見WebContentTypeMapper的文檔。

如果我將Content-Type“ application / json”更改為“ application / x-www-form-urlencoded”,則可以,但是我需要JSON格式的數據。 我缺少任何設置嗎? 請指教。

我添加了自定義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>

這解決了我的問題,也希望其他的幫助。 感謝您的幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM