我已经编写了一个网络服务,在浏览器中启动后可以正常工作。我在这个网络服务中传递了一个客户端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 服务?请问有人能帮助我吗?
[WebGet]
表示webrequest.Method = "GET"
。 - Eser