如何在C#中使用WCF REST服务?

我的合同细节如下。 我正在使用Json响应和请求格式,也使用POST方法。 如何编写客户端以在c#中使用此服务。

[OperationContract()] [WebInvoke(UriTemplate = "/RESTJson_Sample1_Sample1Add", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] int RESTJson_Sample1_Sample1Add(Int32 a, Int32 b, Int32 c); 

尝试如下:

  [OperationContract()] [WebInvoke(UriTemplate = "/RESTJson_Sample1_Sample1Add?A=a&B=b&C=c", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] int RESTJson_Sample1_Sample1Add(Int32 a, Int32 b, Int32 c); var httpWebRequest = (HttpWebRequest)WebRequest.Create("/RESTJson_Sample1_Sample1Add?A=a&B=b&C=c"); httpWebRequest.ContentType = "text/json"; httpWebRequest.Method = methodType;//POST/GET string responseText = ""; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { streamWriter.Write(body);//any parameter } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { responseText = streamReader.ReadToEnd(); } return responseText; 

这里我在WCF REST中有POST方法的工作代码: –

首先使用id,uname和pwd字段创建数据库表。 创建一个存储过程来插入值。

 create procedure [dbo].[sproc_Insertusers] ( @id int out, @uname nvarchar(50), @pwd nvarchar(50) ) as insert into tbl_register ( [uname], [pwd] ) values ( @uname, @pwd ) set @id = @@identity return @id 

创建新的WCF项目

在IService1.cs中

 [ServiceContract] public interface IService1 { [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "user_register/{uname}/{pwd}")] int user_register(string uname,string pwd); } 

在Service1.cs中

  public class Service1 : IService1 { SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["iwealth_db"]); SqlCommand cmd; DataSet ds; SqlDataAdapter da; int result; public int user_register(string uname, string pwd) { cmd = new SqlCommand("sproc_Insertusers", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@uname",uname); cmd.Parameters.AddWithValue("@pwd", pwd); cmd.Parameters.Add("@id", SqlDbType.Int); cmd.Parameters["@id"].Direction = ParameterDirection.Output;//Output parameter cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); result = (int)(cmd.Parameters["@id"].Value); return result;//returning id } } 

在web.config中: –

                                        

构建WCF。 现在,下面的代码是如何使用或使用此WCF服务

创建新网站

添加注册按钮以测试此WCF服务

按钮点击代码: –

  protected void Button1_Click(object sender, EventArgs e) { //in 'sURL' paste WCF service link up to .svc and write -> /user_register/Prateek/1234 //here user_register is service method path and Prateek and 1234 are parameters that will enter to database string sURL = "http://localhost:49271/Service1.svc/user_register/Prateek/1234"; WebRequest wrGETURL; wrGETURL = WebRequest.Create(sURL); wrGETURL.Method = "POST"; wrGETURL.ContentType = @"application/json; charset=utf-8"; HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse; Encoding enc = System.Text.Encoding.GetEncoding("utf-8"); // read response stream from response object StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc); // read string from stream data strResult = loResponseStream.ReadToEnd(); // close the stream object loResponseStream.Close(); // close the response object webresponse.Close(); // assign the final result to text box Response.Write(strResult); } 

要使用WCF Restful服务,不需要在Web.config中进行更改。 找到以下代码来使用WCF restful服务的POST方法。

  DataContractJsonSerializer objseria = new DataContractJsonSerializer(typeof(StudentDetails)); MemoryStream mem = new MemoryStream(); objseria.WriteObject(mem, stu); string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length); WebClient webClient = new WebClient(); webClient.Headers["Content-type"] = "application/json"; webClient.Encoding = Encoding.UTF8; webClient.UploadString("http://localhost:62013/Service1.svc/ADDStudent", "POST", data); 

参考链接

如果您想从C#使用REST服务,可以查看RestSharp 。 请注意,使用WCF,您还可以在不同的端点上使用basicHttp绑定公开相同的方法,并使用SOAP来使用它。

您还可以查看WebChannelFactory,在本文结尾处查看此MSDN教程 。