我已经创建了一个RESTful服务,它提供了以下响应:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">hello</string>
但是,我希望它只返回'你好'。我怎么能这样做?
接口:
[ServiceContract]
public interface IApp
{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
Method = "GET",
UriTemplate = "/ourapi/v1/admin/certificate")]
string retrieveInfo();
}
C#:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class App : IApp
{
public string retrieveInfo()
{
WebOperationContext ctx = WebOperationContext.Current;
var dateValue = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss UTC", CultureInfo.InvariantCulture);
string merchantId = "1234567";
string errorCodeValue = "00";
ctx.OutgoingResponse.ContentType = "text/plain; charset=utf-8";
ctx.OutgoingResponse.Headers.Add("date", dateValue);
ctx.OutgoingResponse.Headers.Add("merchant-id", merchantId);
ctx.OutgoingResponse.Headers.Add("error-code", errorCodeValue);
return "hello";
}
}
答案 0 :(得分:3)
我一直这样做的方法是返回Stream
。我还删除了您的请求和回复,并将BodyStyle
设置为Bare。
[WebInvoke(BodyStyle = WebMessageBodyStyle.Bare,
Method = "GET",
UriTemplate = "/ourapi/v1/admin/certificate")]
Stream retrieveInfo();
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class App : IApp
{
public Stream retrieveInfo()
{
WebOperationContext ctx = WebOperationContext.Current;
var dateValue = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss UTC", CultureInfo.InvariantCulture);
string merchantId = "1234567";
string errorCodeValue = "00";
ctx.OutgoingResponse.ContentType = "text/plain; charset=utf-8";
ctx.OutgoingResponse.Headers.Add("date", dateValue);
ctx.OutgoingResponse.Headers.Add("merchant-id", merchantId);
ctx.OutgoingResponse.Headers.Add("error-code", errorCodeValue);
return New System.IO.MemoryStream(Encoding.UTF8.GetBytes("hello"));
}
}
答案 1 :(得分:0)
您只需拥有两种XML
和JSON
的响应格式即可。但是你可以扩展WCF
以产生你想要的东西。有关详细信息,请参阅article