我创建了以下 Restfull Web 服务:
界面
[ServiceContract]
public interface ISIGService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetTicket/")]
Ticket GetTicket(string user, string pwd);
}
实现
public class SIGService : ISIGService
{
public Ticket GetTicket(string user, string pwd)
{
return new Ticket()
{
Usuario = "xx",
UsuarioNombre = "xxx",
UsuarioId = "xxx"
};
}
契约(Contract)
[DataContract]
public class Ticket
{
[DataMember]
public int UsuarioId { get; set; }
[DataMember]
public string UsuarioNombre { get; set; }
[DataMember]
public string Usuario { get; set; }
}
我需要从网络应用程序使用此服务,并获取类型化对象Ticket
,我已为此提供了一个服务引用。
服务器端代码:
string urlService =
String.Format("http://localhost:22343/SIGService.svc/GetTicket/?user='{0}'&pwd='{1}'",
usuario, password);
var request = (HttpWebRequest)WebRequest.Create(urlService);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
我放置了一个text
变量只是为了得到一些东西,有点在这里丢失了。
我似乎没有得到这个对象,你能给出一些指示吗?
最佳答案
很可能,您只需更改您的网址
http://localhost:22343/SIGService.svc/GetTicket/?user='{0}'&pwd='{1}'
使用正确的REST语法(因为您使用的是REST服务):
http://localhost:22343/SIGService.svc/GetTicket/{user}/{pwd}
示例:
http://localhost:22343/SIGService.svc/GetTicket/daniel/topsecret
不需要 ?
或 user=
或单引号......
这样,{0}
中的值将传递到 user
参数中,{1}
中的值将传递到pwd
参数。
要使用该服务,我建议您查看优秀的RestSharp库,使您可以轻松使用 REST 服务。
你的代码看起来像这样:
// set up the REST Client
string baseServiceUrl = "http://localhost:22343/SIGService.svc";
RestClient client = new RestClient(baseServiceUrl);
// define the request
RestRequest request = new RestRequest();
request.Method = Method.GET;
request.RequestFormat = DataFormat.Xml;
request.Resource = "GetTicket/{user}/{pwd}";
request.AddParameter("user", "daniel", ParameterType.UrlSegment);
request.AddParameter("pwd", "top$ecret", ParameterType.UrlSegment);
// make the call and have it deserialize the XML result into a Ticket object
var result = client.Execute<Ticket>(request);
if (result.StatusCode == HttpStatusCode.OK)
{
Ticket ticket = result.Data;
}
关于c# - 通过 datacontract 使用 WCF Restful 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32284907/