Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I developed one WCF Rest Service. get method and post methods how to call wcf rest service from web client. My code like this

----WCF Interface methods
VB
[OperationContract]
       [WebInvoke(UriTemplate = "UpdateTrackDetails",
           Method = "POST",  RequestFormat = WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
       string UpdateTrackDetails(string trackdetails);


---WCF Implementation of Interface
public string UpdateTrackDetails(string trackdetails)
{

string time = "";
DateTime dt = new DateTime();
try
{
// System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
string result = "0";
TrackDetails _BusTrack = JsonConvert.DeserializeObject<trackdetails>(trackdetails);
time = _BusTrack.TrackTime;
string daa = Convert.ToDateTime(time).ToString("dd/MM/yyyy");
dt = Convert.ToDateTime(daa);
using (var context = new SchoolBusTrackEntities())
{
context.BusTrackDetails.Add(
new BusTrackDetail
{
BusID = Convert.ToInt32(_BusTrack.BusID),
Latitude = _BusTrack.Latitude,
Longitude = _BusTrack.Longitude,
// TrackTime = DateTime.Now
TrackTime = dt,
TrackTime1 = time
}
);
result = context.SaveChanges().ToString();
}
return "result";
}
catch (Exception ex)
{
return ex.Message;
}

}

---WCF Config File
<system.servicemodel>
<services>
<service name="BusTrackService.SchoolBusTrack" behaviorconfiguration="ServiceBehavior">
<endpoint address="" binding="webHttpBinding" contract="BusTrackService.ISchoolBusTrack" behaviorconfiguration="Web">
<identity>
<dns value="localhost">


<endpoint name="mexHttpBinding">
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"
/>


<behaviors>
<servicebehaviors>
<behavior name="ServiceBehavior">
<datacontractserializer maxitemsinobjectgraph="10000000">
<servicemetadata httpgetenabled="true">
<servicedebug includeexceptiondetailinfaults="false">

<behavior>
<servicemetadata httpgetenabled="true">
<servicedebug includeexceptiondetailinfaults="false">


<endpointbehaviors>
<behavior name="Web">
<datacontractserializer maxitemsinobjectgraph="10000000">
<webhttp helpenabled="true" defaultoutgoingresponseformat="Json" defaultbodystyle="Bare" automaticformatselectionenabled="true">
<!--<webhttp>-->



<bindings>
<webhttpbinding>
<binding maxreceivedmessagesize="2147483647">
<readerquotas maxarraylength="2147483647" maxstringcontentlength="2147483647">



<servicehostingenvironment multiplesitebindingsenabled="true">

<system.webserver>
<modules runallmanagedmodulesforallrequests="true">
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directorybrowse enabled="true">

<system.diagnostics>
<trace autoflush="true"> <sources>

switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners> <add name="sdt">
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="serviceLog3.xml" />




----My Client Calling Method
public string call1()
{
string sURL = "http://localhost:52305/SchoolBusTrack.svc/UpdateTrackDetails";
BusTrack1 _test = new BusTrack1();
_test.BusID = txtBusID.Text;
_test.Latitude = txtLatitude.Text;
_test.Longitude = txtLongitude.Text;
_test.TrackTime = txtTrackTime.Text;
_test.TrackTime1 = txtTrackTime1.Text;

string JsonString = new JavaScriptSerializer().Serialize(_test);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(sURL);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";//GET
string responseText = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(JsonString);//any parameter
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = streamReader.ReadToEnd();
}
return responseText;
}

---calling Differnt way in client side

string reqUrl = "http://192.168.1.46/BusWCF/SchoolBusTrack.svc/UpdateTrackDetails";

BusTrack1 _Bus = new BusTrack1();
_Bus.BusID = BusID;
_Bus.Latitude = Latitude;
_Bus.Longitude = Longitude;
_Bus.TrackTime = TrackTime;
_Bus.TrackTime1 = TrackTime1;

var JsonString = new JavaScriptSerializer().Serialize(_Bus);
// Response.Write(JsonString);
byte[] bytes = new UTF8Encoding().GetBytes(JsonString.ToString());
WebRequest request = WebRequest.Create(reqUrl);
request.Timeout = 2000;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = bytes.Length;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(JsonString);
}
WebResponse responce = request.GetResponse();
Stream reader = responce.GetResponseStream();
StreamReader sReader = new StreamReader(reader);
string outResult = sReader.ReadToEnd();
sReader.Close();

but i got the error

The remote server returned an error: (400) Bad Request.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request.

please tel what is my error..

Thanks and Regards
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900