我创建了一个wcf休息服务。你可以看到它的详细信息:
[ServiceContract]
public interface INewsRepository
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/AddNews", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool Add(News entity);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/DeleteNews/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool Remove(string id);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/EditNews", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool Edit(News entity);
}
我在我的客户端中将此服务称为:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Script.Serialization;
using CMSManagement.Domain.Entity;
using UPTO.UI.Infrastructure.Configuration;
using System.Text;
namespace UPTO.UI.Services
{
public class NewsRepository : IServiceRepository<News>
{
private WebClient ClientRequest;
private MemoryStream ms;
private DataContractJsonSerializer serializerToUplaod;
public string ServiceHostName = "http://cmsmanagement"+ ServiceServer.Address;
public NewsRepository()
{
ClientRequest = new WebClient();
ClientRequest.Headers["Content-type"] = "application/json";
ms= new MemoryStream();
}
public bool Add(News data)
{
serializerToUplaod = new DataContractJsonSerializer(typeof(News));
serializerToUplaod.WriteObject(ms, data);
string Result = System.Text.Encoding.UTF8.GetString(ClientRequest.UploadData(ServiceHostName+"/NewsRepository.svc/AddNews", "POST", ms.ToArray()));
return Result.ToLower().Equals("true");
}
public bool Delete(string id)
{
byte[] data = ClientRequest.UploadData(ServiceHostName+"/NewsRepository.svc/DeleteNews/"+id, "POST", ms.ToArray());
string Result = System.Text.Encoding.UTF8.GetString(data);
return Result.ToLower().Equals("true");
}
public bool Edit(News data)
{
serializerToUplaod = new DataContractJsonSerializer(typeof(News));
serializerToUplaod.WriteObject(ms, data);
string Result = System.Text.Encoding.UTF8.GetString(ClientRequest.UploadData("http://localhost:47026/NewsRepository.svc/EditNews", "POST", ms.ToArray()));
return Result.ToLower().Equals("true");
}
}
}
问题是我服务的编辑部分: 当我调用我的编辑方法时,我在wcf日志中收到此错误:
The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.
答案 0 :(得分:1)
最后我发现我应该移动
ClientRequest.Headers["Content-type"] = "application/json";
从构造函数到我的Edit
方法。为什么?