【问题标题】:How to consume WCF REST Service in C#?如何在 C# 中使用 WCF REST 服务?
【发布时间】:2013-07-08 01:17:55
【问题描述】:

我的合同详情如下。我正在使用 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);

【问题讨论】:

  • 请不要只求我们为您解决问题。向我们展示如何尝试自己解决问题,然后向我们确切地展示结果是什么,并告诉我们您为什么觉得它不起作用。请参阅“What Have You Tried?”了解您真正需要阅读的优秀文章。

标签: c# wcf rest wcf-rest


【解决方案1】:

这里我有 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 中:-

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="iwealth_db"  value="Data Source=localhost;Initial Catalog=iwealth; Trusted_Connection=true"/>      
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="iWealthService.Service1" behaviorConfiguration="ServiceBehaviour">
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint address ="" binding="webHttpBinding" contract="iWealthService.IService1" behaviorConfiguration="web">
          <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

构建 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);
    }

【讨论】:

  • 感谢 Prateek Gupta,分享代码。它对我有很大帮助。对于宁静的服务,在消费服务时不需要添加服务引用,是这样吗?实际上我试图在消费时添加服务引用.这就是为什么我的客户端网络配置文件不包含端点。你的代码帮助了我。我可以直接通过浏览器使用服务吗?意味着在浏览器中输入 url 并点击。'localhost:49271/Service1.svc/user_register/Prateek/1234'.I 想要这样。意味着客户端可以在浏览器中输入 url 和命中,命中后客户想要确认
  • 上面的例子是'POST'方法。如果你把 'GET' 放在 IService1.cs 文件中,这也将在浏览器中工作。
  • 感谢您的评论。我已经做到了,它工作正常。我可以通过浏览器对其进行测试。但最好使用 post 方法而不是 get。现在我们为客户端提供接口进行检查url请求。所以不需要浏览器。
【解决方案2】:

要使用 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);

Reference link

【讨论】:

    【解决方案3】:

    尝试如下:

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

    【讨论】:

    • 很好的例子。一个问题。您传递给 WebRequest.Create 方法的“serviceURL”是 RESTful Uri htttp://{domain name}/RestJson_Sample...(使用上面的示例)?
    • 假设如果我有 3 个整数参数,我该如何传递?
    • 因为我们使用的是 POST 方法,但这里我们通过查询字符串传递值。对吗?
    • 我的 Uri 模板应该是这样的 "UriTemplate = "/RESTJson_Sample1_Sample1Add"。有了这个,我如何通过客户端传递三个参数?还请让我知道我应该在“body”参数中传递什么在你的例子中。
    • 我在“var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();”处遇到错误错误详情:远程服务器返回错误:(404) Not Found.
    【解决方案4】:

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

    你也可以看看WebChannelFactory,看文末this MSDN tutorial

    【讨论】:

    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 2020-02-08
    相关资源
    最近更新 更多