我正嘗試將一些JSON數據發送到我在c#和wcf中創建的服務。在我的提琴手POST請求如下:將JSON數據發佈到WCF服務時出現錯誤415
提琴手:
Request Header
User-Agent: Fiddler
Host: localhost
Content-Length: 29
Content-Type: application/json; charset=utf-8
Request Body
{sn:"2705", modelCode:1702 }
下面是服務接口。使用該WebInvoke屬性來管理POST請求
[ServiceContract]
public interface IProjectorService
{
[WebInvoke(Method="POST", UriTemplate="projectors", RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
[OperationContract]
void RecordBreakdown(Record record);
}
服務接口的實現需要到參數傳遞的變量和使用ADO將此數據發送到SQL數據庫。
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public partial class ProjectorService : IProjectorService
{
public void RecordBreakdown(Record record)
{
//ado code to send data to db (ie do record.SerialNumber...
}
}
POCO對象來表示多個參數
[DataContract]
public class Record
{
[DataMember]
public string SerialNumber { get; set; }
[DataMember]
public int ModelCode { get; set; }
}
.svc文件
<%@ ServiceHost Language="C#" Debug="true" Service="ProjectorService" CodeBehind="~/App_Code/ProjectorService.cs" %>
Web.config文件:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
在小提琴手,當我點擊「執行「,我收到錯誤415」不支持的媒體類型PE」。我目前的想法是,在我的Projector服務類中,也許我應該創建一個響應對象併發回200代碼?!
多數民衆贊成在工作。我認爲web綁定是使用svc文件中的工廠方法自動生成的(我還沒有包含它)。除了這些更改,我需要將'BodyStyle = WebMessageBodyStyle.Bare'添加到服務方法中,因爲JSON數據未包含在另一個對象中。 – beaumondo