【发布时间】: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