gpt4 book ai didi

c# - 在 C# 中将 HTTP Accept 和 Content-Type header 都设置为 "application/xml"

转载 作者:数据小太阳 更新时间:2023-10-29 01:47:33 24 4
gpt4 key购买 nike

我用 C# 创建了一个网络服务 (REST)。现在我希望当有人使用它时,它应该根据 header 返回 JSON 或 XML。我找到了一个很好的tutorial here .我跟着它,但我不知道它在哪里说 set both the HTTP Accept and Content-Type headers to "application/xml",我这样调用它 http://localhost: 38477/社交/姓名。如果我的问题对你来说不是很清楚,我可以回答任何问题谢谢这是我的代码

[WebInvoke(UriTemplate = "{Name}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
public MyclassData Get(string Name)
{
// Code to implement
return value;

}

最佳答案

您使用什么框架(看起来像旧的 WCf Web Api)来构建您的 RESTful 服务?我强烈推荐使用 Microsoft 的新 MVC4 Web API。它真正开始成熟并极大地简化了 RESTful 服务的构建。这是 WCF Web API 即将停用的 future 将要支持的内容。

您只需将 ModelClass 作为返回类型返回,它会根据请求接受 header 自动将其序列化为 XML 或 JSON。您可以避免编写重复代码,您的服务将支持范围广泛的客户。

public class TwitterController : ApiController
{
DataScrapperApi api = new DataScrapperApi();
TwitterAndKloutData data = api.GetTwitterAndKloutData(screenName);
return data;
}

public class TwitterAndKloutData
{
// implement properties here
}

链接

您可以通过仅下载 MVC4 2012 RC 获得 MVC4 Web Api,也可以下载整个 Visual Studio 2012 RC。

MVC 4:http://www.asp.net/mvc/mvc4

对比 2012:http://www.microsoft.com/visualstudio/11/en-us/downloads


对于原始的 wcf web api,请尝试一下。检查接受 header 并根据其值生成您的响应。

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;

您可以在发起请求的任何客户端上设置接受 header 。这将根据您用于发送请求的客户端类型而有所不同,但任何 http 客户端都可以添加 header 。

WebClient client = new WebClient();
client.Headers.Add("accept", "text/xml");
client.DownloadString("domain.com/service");

要访问您将使用的响应 header

WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";

其他资源:http://dotnet.dzone.com/articles/wcf-rest-xml-json-or-both

关于c# - 在 C# 中将 HTTP Accept 和 Content-Type header 都设置为 "application/xml",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11385031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com