Я использую метод 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» с пространством имен «IRestService / JSONData») содержит нераспознанное значение формата тела http «Json». Ожидаемое значение формата тела - «Raw». Это может быть связано с тем, что для привязки не настроен WebContentTypeMapper. Дополнительную информацию см. В документации WebContentTypeMapper.
если я изменю Content-Type «application / json» на «application / x-www-form-urlencoded», он будет работать, но мне нужны данные в формате JSON. Есть ли какая-то настройка, с которой мне не хватает? Пожалуйста посоветуй.
WebContentTypeMapper
. 27.10.2016