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

xav*_*xav 3 c# rest web-services webservice-client webservices-client

我写了一个web服务,在浏览器启动时工作正常.我在这个webservice中传递一个客户端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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我无法消耗它.我的代码是:

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);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Pan*_*vos 13

异常非常明确 - 如果要从REST服务检索数据,则不能使用POST ,除非它允许.你应该使用GETPOST不是改变,或者根本不改变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);
}
Run Code Online (Sandbox Code Playgroud)

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