【问题标题】:How to consume Rest Web service in c#如何在 C# 中使用 Rest Web 服务
【发布时间】:2015-09-03 07:14:30
【问题描述】:

我编写了一个 web 服务,它在浏览器启动时运行良好。我在这个 web 服务中传递了一个客户端 ID,然后返回一个包含客户端名称的字符串,我们通过如下方式传递它:http://prntscr.com/8c1g9z

我创建服务的代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace RESTService.Lib
{
    [ServiceContract(Name = "RESTDemoServices")]
    public interface IRESTDemoServices
    {
        [OperationContract]
        [WebGet(UriTemplate = "/Client/{id}", BodyStyle = WebMessageBodyStyle.Bare)]
        string GetClientNameById(string Id);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RestDemoServices:IRESTDemoServices
    {
        public string GetClientNameById(string Id)
        {
            return ("Le nom de client est Jack et id est : " +Id);
        }
    }
}

但我不能消费它。我的代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Http;
using System.Net;
using System.IO;
namespace ConsumerClient
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {   
            System.Net.HttpWebRequest webrequest = (HttpWebRequest)System.Net.WebRequest.Create("http://localhost:8000/DEMOService/Client/156");
            webrequest.Method = "POST";
            webrequest.ContentType = "application/json";
            webrequest.ContentLength = 0;
            Stream stream = webrequest.GetRequestStream();
            stream.Close();
            string result;
            using (WebResponse response = webrequest.GetResponse()) //It gives exception at this line liek this http://prntscr.com/8c1gye
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                    Label1.Text = Convert.ToString(result);
                }
            }
        }
    }
}

我得到一个像这样的异常http://prntscr.com/8c1gye 如何使用 Web 服务。有人可以帮我吗?

【问题讨论】:

  • [WebGet] 表示webrequest.Method = "GET"

标签: c# web-services rest webservice-client webservices-client


【解决方案1】:

例外情况很明显 - 如果您想从 REST 服务中检索数据,则不能使用 POST,除非它允许。您应该使用GET 而不是POST,或者干脆不要更改request.Method。默认为GET

您不需要做任何特别的事情来“使用” REST 服务 - 本质上它们就像任何其他 URL 一样工作。 HTTP POST 动词表示您想要创建 一个新资源,或发布表单数据。要检索资源(页面、API 响应等),请使用 GET。

这意味着您可以使用任何与 HTTP 相关的 .NET 类来调用 REST 服务 - HttpClient(首选)、WebClient 或原始 HttpWebRequest。

SOAP 服务使用 POST 来获取数据,现在每个人(包括 SOAP 的创建者)都认为这是一个设计错误。

编辑

为了明确这一点,使用GET 意味着没有内容,并且不需要或不允许与内容相关的标头或操作。和下载任何 HTML 页面一样:

var url="http://localhost:8000/DEMOService/Client/156";
var webrequest = (HttpWebRequest)System.Net.WebRequest.Create(url);

using (var response = webrequest.GetResponse()) 
using (var reader = new StreamReader(response.GetResponseStream()))
{
    var result = reader.ReadToEnd();
    Label1.Text = Convert.ToString(result);
}

您甚至可以将 URL 直接粘贴到浏览器以获得相同的行为

【讨论】:

  • 附加信息:无法发送具有此动词类型的内容主体。在行 Stream stream = webrequest.GetRequestStream();获取后
  • 为什么传递一个body?您已经使用 Id 参数定义了一个操作,而 Id 实际上是 URL 的一部分。将 ID 放在请求 URL 中。对http://localhost:8000/DEMOService/Client/156 的简单网络请求就足够了。即使是 URL 上的 WebClient.GetString 也可以使用
  • 感谢您的回答。但我在消费者代码中也做了同样的事情。请参阅: System.Net.HttpWebRequest webrequest = (HttpWebRequest)System.Net.WebRequest.Create("localhost:8000/DEMOService/Client/156"); 但仍然不工作
  • 代码的 rest 就像您在尝试进行 POST 一样 - 您不需要指定内容类型或者对请求流做任何事情。只需立即调用request.GetResponse(),就像您尝试调用any URL 时一样
  • raw HttWebRequest. 是一个错字。
【解决方案2】:

此代码示例是一个简单示例,说明如何在 C# 中使用 REST Web 服务:

// http://localhost:{portno}/api/v1/youractionname?UserName=yourusername&Passowrd=yourpassword [HttpGet]

[ActionName("Youractionname")]

public Object Login(string emailid, string Passowrd)
{
    if (emailid == null || Passowrd == null)
    {
        geterror gt1 = new geterror();
        gt1.status = "0";
        gt1.msg = "All field is required";
        return gt1;
    }
    else
    {
        string StrConn = ConfigurationManager.ConnectionStrings["cn1"].ConnectionString;
        string loginid = emailid;
        string Passwrd = Passowrd;
        DataTable dtnews = new DataTable();
        SqlConnection con = new SqlConnection(StrConn);
        con.Open();
        SqlCommand cmd = new SqlCommand("sp_loginapi_app", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter p1 = new SqlParameter("@emailid", loginid);
        SqlParameter p2 = new SqlParameter("@password", Passowrd);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        cmd.Parameters.Add(p1);
        cmd.Parameters.Add(p2);
        da.Fill(dtnews);
        if (dtnews.Rows[0]["id"].ToString() == "-1")
        {
            geterror gt1 = new geterror();
            gt1.status = "0";
            gt1.msg = "Invalid Username or Password";
            con.Close();
            return gt1;
        }
        else
        {
            dtmystring.Clear();
            dtmystring.Columns.Add(new DataColumn("id", typeof(int)));
            dtmystring.Columns.Add(new DataColumn("Name", typeof(string)));
            dtmystring.Columns.Add(new DataColumn("Password", typeof(string)));
            dtmystring.Columns.Add(new DataColumn("MobileNo", typeof(string)));
            dtmystring.Columns.Add(new DataColumn("Emailid", typeof(string)));
            DataRow drnew = dtmystring.NewRow();
            drnew["id"] = dtnews.Rows[0]["id"].ToString();
            drnew["Name"] = dtnews.Rows[0]["Name"].ToString();
            drnew["Password"] = dtnews.Rows[0]["Password"].ToString();
            drnew["MobileNo"] = dtnews.Rows[0]["MobileNo"].ToString();
            drnew["Emailid"] = dtnews.Rows[0]["emailid"].ToString();
            dtmystring.Rows.Add(drnew);
            gt.status = "1";
            gt.msg = dtmystring;
            con.Close();
            return gt;
        }
    }
}

【讨论】:

  • C# 中 Rest web 服务的好例子。
  • 感谢@Mannam Brahmam!
  • 这是一个非常简单的rest web api示例。
  • 其实,这根本不是一个 REST 消费者示例,它是一个 REST 服务本身的示例,并没有展示如何使用它。此外,这里有很多处理与 REST 主题无关的数据库的代码。您可能希望改进您​​的答案以展示如何使用它。
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-03
  • 2013-07-08
  • 2017-11-06
  • 1970-01-01
相关资源
最近更新 更多