简体   繁体   English

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

[英]How to consume Rest Web service in c#

I have written a webservice which on browser launch works fine. 我写了一个web服务,在浏览器启动时工作正常。 I pass a client id in this webservice and then returns a string containing the client name and it which we passed like this: http://prntscr.com/8c1g9z 我在这个webservice中传递一个客户端ID,然后返回一个包含客户端名称的字符串,我们通过这样的字符串: http//prntscr.com/8c1g9z

My code for creating service is: 我创建服务的代码是:

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

But I am not able to consume it. 但我无法消耗它。 My code is: 我的代码是:

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

I get an exception like this http://prntscr.com/8c1gye How to consume the web service. 我得到一个像这样的例外http://prntscr.com/8c1gye如何使用Web服务。 Could someone please help me ? 有人可以帮帮我吗?

The exception is pretty clear - you can't use POST if you want to retrieve data from a REST service, unless it allows it. 异常非常明确 - 如果要从REST服务检索数据,则不能使用POST,除非它允许。 You should use GET instead of POST , or simply don't change request.Method . 您应该使用GET而不是POST ,或者只是不要更改request.Method By default it's GET . 默认情况下它是GET

You don't need to do anything special to "consume" REST services - essentially they work just like any other URL. 您不需要做任何特殊的“消费”REST服务 - 实质上它们就像任何其他URL一样工作。 The HTTP POST verb means that you want to create a new resource, or post form data. HTTP POST动词表示您要创建新资源或发布表单数据。 To retrieve a resource (page, API response etc) you use GET. 要检索资源(页面,API响应等),请使用GET。

This means that you can use any of the HTTP-related .NET classes to call a REST service - HttpClient (preferred), WebClient or raw HttpWebRequest. 这意味着您可以使用任何与HTTP相关的.NET类来调用REST服务 - HttpClient(首选),WebClient或原始HttpWebRequest。

SOAP services used POST both for getting and sending data, which is now considered a design mistake by everyone (including the creators of SOAP). SOAP服务使用POST来获取发送数据,现在每个人(包括SOAP的创建者)都认为这是一个设计错误。

EDIT 编辑

To make this clear, using a GET means there is no content and no content related headers or operations are needed or allowed. 为了清楚起见,使用GET意味着没有内容,也不需要或不允许与内容相关的标题或操作。 It's the same as downloading any HTML page: 这与下载任何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);
}

You can even paste the URL directly to a browser to get the same behaviour 您甚至可以将URL直接粘贴到浏览器以获得相同的行为

This code example is a simple example of how to consume a REST web service in C#: 此代码示例是如何在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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM