在C#Restful Client,ASP.net Client中创建C#Restful Service and Consume [英] Create C# Restful Service and Consume in C# Restful Client, ASP.net Client

查看:144
本文介绍了在C#Restful Client,ASP.net Client中创建C#Restful Service and Consume的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨亲爱的:

我在C#中创建了一个Restful Service,现在我想在C#Restful Client中使用我的这个服务。客户端可能是控制台客户端,但首选Asp.net客户端。

我已经尝试了很多教程,但到目前为止还没有成功,

请建议我一些工作样本,



我的项目代码如下:

以下是Servie项目中 Web.Config文件的代码:



Hi Dear:
I have Created a Restful Service in C#, and Now i want to use my this Service in C# Restful Client. Client may be a Console Client, but Asp.net Client is preferred.
I have tried a lot more Tutorials, but no Success till now,
Please suggest me some Working Sample,

My Project code is as follow:
Here is the code of Web.Config File in Servie Project:

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>

    <services>
      <service name="Restful.Restful" behaviorConfiguration="ServiceBehaviour">
        <endpoint address="" binding="webHttpBinding" contract="Restful.IRestful" behaviorConfiguration="web">

        </endpoint>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="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>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <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.webServer>

</configuration>







我的< b> IRestful.cs 代码





我的项目(Restful Service)名称很休息,




My IRestful.cs Code


My Project(Restful Service) Name is Restful,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace Restful
{
    [ServiceContract]
    public interface IRestful
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "name/id={id}")]
        string test(string id);

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "xml/?id={id}")]
        string xdata(string id);

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/?id={id}")]
        string jdata(string id);

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "sum/?a={a}&b={b}")]
        string sum(int a, int b);
    }
}





我的 Restful.svc.cs 代码:



My Restful.svc.cs Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace Restful
{
    public class Restful : IRestful
    {
        #region IRestService Members

        public string test(string id)
        {
            return "Testing Phase is Continued. :" + id;
        }
        public string xdata(string id)
        {
            return "Your Requested XML Product is :" + id;
        }

        public string jdata(string id)
        {
            return "Your Requested XML Product is :" + id;
        }

        public string sum(int a, int b)
        {
            return "Sum of Numbers is: " + (a + b);
        }

        #endregion
    }
}







我尝试使用ASP.net消费服务,我的ASP.net项目名称是WebClient

以下是 WebForm.aspx.cs文件的代码:




I have Tried to Consume Service using ASP.net, My ASP.net project name is WebClient
Here is the code of WebForm.aspx.cs File:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Http;

namespace WebClient
{
    public partial class WebForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage msg = client.GetAsync("http://localhost:27629/Restful.svc/sum/?a=23&b=90").ContinueWith<httpresponsemessage>;
            HttpContent strm = msg.Content();
            var data = strm.ReadAsStreamAsync();
            Label1.Text = Convert.ToString(data.Result);
        }
    }
}





这是 WebForm.aspx文件的代码:





Here is the code of WebForm.aspx file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm.aspx.cs" Inherits="WebClient.WebForm" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <div>

    </div>
    </form>
</body>
</html>









请参考我的解决方案,这可能导致摆脱这个问题....

在此先感谢...





Please refer me tos solution, that may lead to get rid of this problem....
Thanks In Advance...

推荐答案

有两种方法可以从服务中获取数据一个是XML,另一个是JSON。

你选择了xml,你收到的数据是XML模式的格式,你只需要将它转换成所需的格式。

我举个例子,



There are two ways to get the data from service one is XML and other one is JSON.
you chose xml the data you received is in the format of XML schema you only have to convert it into required format.
I just give you an example,

HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("your url with args");
webrequest.Method = "POST";
webrequest.ContentType = "application/json";
webrequest.ContentLength = 0;
Stream stream = webrequest.GetRequestStream();
stream.Close();
string result;
using (WebResponse response = webrequest.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
}





结果变量包含xml架构为字符串

所以,现在根据您的需要进行转换。



为此,您需要将数据发送到您需要的数据,如字符串,列表或数据集

来自服务。

困难的是从服务中检索数据集,其中包含具有列数的记录列表。

我只给你核心片段





The result variable contains xml schema as string
So, now convert into as per your need.

For that you need to send the data into your required need like string, list or dataset
from the service.
The difficult one is retreiving the dataset from the service which contains a list of records with number of columns.
I just give you the core snippet

DataSet ds = new DataSet();
ds.Tables.Clear();
XmlElement exelement;
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);//Load the XML schema string into a XML document
exelement = doc.DocumentElement;//Get the XML element from the document
if (exelement != null)
{
XmlNodeReader nodereader = new XmlNodeReader(exelement);/read the nodes in the XML element
ds.ReadXml(nodereader, XmlReadMode.Auto);//Read the XML nodes and load it in the dataset
}





希望它有帮助......!



Hope it helps...!


亲爱的会员8775683我了解你,我几天前也学到了这一点。如果我对你做了编码意味着你不会自学。

所以我很快就给你一个明确的想法我会写一篇文章以便帮助你。



这是我的服务,

Dear Member 8775683 i understand you, i also learnt this some days ago. If i did the coding to you means you dont get learnt on yourself.
So i just gave you clear idea soon i will write an article so that help you.

This is my service,
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate="CheckLogin/{userName}/{password}")]
string CheckLogin(string userName,string password);





我检查数据并仅以json格式返回字符串值。



I checked the data and returns a string value only in json format.

public string CheckLogin(string userName, string password)
        {
            try
            {
                ds = null;
                data = "";
                integerValue = dbServices.CheckLogin(userName, password);
                if (integerValue >= 1)
                {
                    Status= "SUCCESS";
                }
                else
                    Status= "FAILED";
            }
            catch (Exception ex)
            {
            }
            return Status;
        }





我在客户端消费如下,





and i consume it at the client side as following,

HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url + "CheckLogin" + "/" + txtUserName.Text.Trim().ToString() + "/" + txtPassword.Text.Trim().ToString());
                   webrequest.Method = "POST";
                   webrequest.ContentType = "application/json";
                   webrequest.ContentLength = 0;
                   Stream stream = webrequest.GetRequestStream();
                   stream.Close();
                   string result;
                   using (WebResponse response = webrequest.GetResponse())
                   {
                       using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                       {
                           result = reader.ReadToEnd();
                       }
                   }
                   result = result.Substring(1, result.Length - 2);



i只需手动编码字符串结果值即可获得我的需求。

您可以通过JSON序列化和反序列化方法来获取数据如你所愿。



你可以从以下链接获得JSON方法。

http://james.newtonking.com/projects/json-net.aspx [ ^ ]



它可能对你有所帮助



并回答您在消费过程中遇到的错误

查看以下链接您可能会得到一些想法

如何使用或使用 - wcf-service [ ^ ]

如何使用-wcf-service-in [ ^ ]

http://technetsharp.wordpress.com / 2012/04/18 / use-wcf-service-in-web-application-for-beginners / [ ^ ]


i just hand code the string result value to get my need.
you may JSON serialize and deserialize methods to get the data as you need.

You may get that JSON methods from the following link.
http://james.newtonking.com/projects/json-net.aspx[^]

It may help you

and to answer the error you got faced is occured during the consumption
look these following links you may get some ideas
how-to-consume-or-use-wcf-service[^]
how-to-consume-wcf-service-in[^]
http://technetsharp.wordpress.com/2012/04/18/use-wcf-service-in-web-application-for-beginners/[^]


这篇关于在C#Restful Client,ASP.net Client中创建C#Restful Service and Consume的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆