0

Hi I used Newtonsoft to build the WCF service in C#. I also have a test website to test my service. When I viewed the WCF service in the browser, it shows. If I used the website to call the service, there is the error :

"The remote server returned an error: (400) Bad Request.

I didn't closed the WCF service in browser. I am not sure whether the website or WCF service cause the error.

There is my WCF service:

[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;
}

There is my method in the website to call the service:

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;
}
user819774
  • 1,456
  • 1
  • 19
  • 48

1 Answers1

0

the 404 you are experiencing is not related to Newtonsoft.Json in any way. Your OperationContract specifies BookingInfo/JSON in the UriTemplate property of the WebInvoke Attribute

[WebInvoke(Method = "POST",UriTemplate = "BookingInfo/JSON/")]        
BookingResult Booking (string bookInfo);

therefore the URL for your client should be

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

heres an MSDN link for further info about the WebInvoke attribute

user1859022
  • 2,585
  • 1
  • 21
  • 33
  • I changed the URL as you suggest, but I got another error, "The remote server returned an error: (400) Bad Request." – user819774 Sep 24 '18 at 16:48
  • any particular reason you are using the generic `WebClient` instead of `HttpClient` ? have a look at https://learn.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/ or https://stackoverflow.com/questions/4015324/how-to-make-http-post-web-request – user1859022 Sep 25 '18 at 07:41