如何在C#中使用Rest Web服务

5
我已经编写了一个网络服务,在浏览器中启动后可以正常工作。我在这个网络服务中传递了一个客户端ID,然后返回一个字符串,其中包含我们传递的客户端名称和IT信息,如下所示: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 服务?请问有人能帮助我吗?


2
[WebGet] 表示 webrequest.Method = "GET" - Eser
2个回答

15
异常情况很明显 —— 除非允许,否则您不能使用 POST 从 REST 服务中检索数据。您应该使用 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粘贴到浏览器中以获得相同的行为

1
附加信息:无法使用此动词类型发送内容主体。在GET之后的行中,Stream stream = webrequest.GetRequestStream(); - xav xav
谢谢您的回答。但是我已经在消费者代码中做了同样的事情。请看: System.Net.HttpWebRequest webrequest = (HttpWebRequest)System.Net.WebRequest.Create("http://localhost:8000/DEMOService/Client/156"); 但仍然不起作用。 - xav xav
是代码的其余部分表现得好像你正在尝试进行POST - 你不需要指定内容类型或对请求流做任何事情。只需立即调用request.GetResponse(),就像在尝试调用任何URL时一样。 - Panagiotis Kanavos
“raw HttWebRequest.”是一个打字错误。 - Amit Kumar Ghosh
异常是关于请求内容和头部的问题,而不是参数。GET就像在Web浏览器中输入URL一样-如果你可以在浏览器中得到响应,那么你可以使用HttpWebRequest仅通过URL获取响应。 - Panagiotis Kanavos
显示剩余2条评论

-1

这个代码示例是一个简单的例子,展示了如何在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
谢谢@Mannam Brahmam! - Manish sharma
这是一个非常简单的REST Web API示例。 - Manish sharma
2
实际上,这不是一个REST消费者的示例,而是一个REST服务本身的示例,并且并没有展示如何_消费_它。此外,这里有很多与数据库相关的代码,与REST主题无关。您可能希望改进您的答案以展示如何消费它。 - Abel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接