在wcf服务中使用Newtonsoft.Json会出错

时间:2018-09-24 13:43:44

标签: c# wcf json.net

嗨,我使用Newtonsoft在C#中构建WCF服务。我也有一个测试网站来测试我的服务。当我在浏览器中查看WCF服务时,它会显示出来。 如果我使用该网站致电该服务,则出现错误:

  

“远程服务器返回错误:(400)错误的请求。

我没有在浏览器中关闭WCF服务。我不确定是网站还是WCF服务引起了错误。

我的WCF服务是

[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Xml,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,         
UriTemplate = "BookingInfo/JSON/")]        
BookingResult Booking (BookInfo bookInfo);




[DataContract]
public class BookInfo
{
    [DataMember]
    public Int64 RoomID;

    [DataMember]
    public Int64 locationID;

    [DataMember]
    public DateTime dateTime;

    [DataMember]
    public string name;
}

[DataContract]
public class BookingResult
{
    [DataMember]
    public bool isSucceed;
}


public BookingResult Booking(string inputClass)
{
    BookInfo bk = JsonConvert.DeserializeObject<BookInfo>(inputClass);
    BookingResult result = new BookingResult();
    if (bk.dateTime < DateTime.Now)
    {
        result.isSucceed = false;
    }
    else { result.isSucceed = true; }
    return result;
}

我的网站上有调用该服务的方法:

private string callService(BookInfo input)
{
    string serviceUrl = "http://localhost:17154/CS/Services/Service.svc/BookingInfo/JSON/";           
    var stringPayload = JsonConvert.SerializeObject(input);      
    WebClient client = new WebClient();

    client.Headers["Content-type"] = "application/json";
    client.Encoding = Encoding.UTF8;
    string rtn = client.UploadString(serviceUrl, "POST", stringPayload);
    return rtn;
}

1 个答案:

答案 0 :(得分:0)

您遇到的404与Newtonsoft.Json毫无关系。 您的OperationContractUriTemplate属性

WebInvoke属性中指定 BookingInfo / JSON
[WebInvoke(Method = "POST",UriTemplate = "BookingInfo/JSON/")]        
BookingResult Booking (string bookInfo);

因此,您的客户的网址应为

string serviceUrl = "http://localhost:17154/CS/Services/Service.svc/BookingInfo/JSON/";           

此处有一个MSDN链接,以获取有关WebInvoke属性的更多信息