use*_*118 7 c# xml wcf json c#-4.0
我在C#中创建了一个Web服务(REST).现在我希望当有人使用它时,它应该按照Header返回JSON或XML.我在这里找到了一个非常好的教程.我跟着它,但我不知道它在哪里说set both the HTTP Accept and Content-Type headers to "application/xml",我这样称呼它http://localhost:38477/social/name.如果我的问题不是很清楚,我可以回答任何问题,谢谢,这是我的代码
[WebInvoke(UriTemplate = "{Name}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
public MyclassData Get(string Name)
{
// Code to implement
return value;
}
Run Code Online (Sandbox Code Playgroud)
你使用什么框架(看起来像旧的WCf Web Api)来构建你的RESTful服务?我强烈建议使用Microsofts新的MVC4 Web API.它真正开始成熟并大大简化了构建RESTful服务.它将在未来WCF Web API即将停止的情况下得到支持.
您只需将ModelClass作为返回类型返回,它将根据请求接受标头自动将其序列化为XML或JSON.您可以避免编写重复的代码,并且您的服务将支持广泛的客户端.
public class TwitterController : ApiController
{
DataScrapperApi api = new DataScrapperApi();
TwitterAndKloutData data = api.GetTwitterAndKloutData(screenName);
return data;
}
public class TwitterAndKloutData
{
// implement properties here
}
Run Code Online (Sandbox Code Playgroud)
链接
您可以通过下载MVC4 2012 RC获得MVC4 Web Api,也可以下载整个Visual Studio 2012 RC.
MVC 4:http://www.asp.net/mvc/mvc4
VS 2012:http://www.microsoft.com/visualstudio/11/en-us/downloads
对于原始的wcf web api,请试一试.检查接受标头并根据其值生成响应.
var context = WebOperationContext.Current
string accept = context.IncomingRequest.Accept;
System.ServiceModel.Chanells.Message message = null;
if (accept == "application/json")
message = context.CreateJsonResponse<TwitterAndCloutData>(data);
else if (accept == "text/xml")
message = context.CreateXmlResponse<TwitterAndCloutData>(data);
return message;
Run Code Online (Sandbox Code Playgroud)
您可以在发起请求的任何客户端上设置接受标头.这将根据您用于发送请求的客户端类型而有所不同,但任何http客户端都可以添加标头.
WebClient client = new WebClient();
client.Headers.Add("accept", "text/xml");
client.DownloadString("domain.com/service");
Run Code Online (Sandbox Code Playgroud)
要访问您将使用的响应标头
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
Run Code Online (Sandbox Code Playgroud)
其他资源:http://dotnet.dzone.com/articles/wcf-rest-xml-json-or-both