在 C# 中将 HTTP Accept 和 Content-Type 标头设置为“application/xml”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11385031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
set both the HTTP Accept and Content-Type headers to "application/xml" in C#
提问by user1391118
I created a web service (REST) in C#. Now I want that when someone uses it, it should return JSON or XML as per Header. I found a very good tutorial here. I followed it but I dont know where it says set both the HTTP Accept and Content-Type headers to "application/xml", I am calling it in this way http://localhost:38477/social/name. I can answer to any question if my question is not very clear to you
Thanks
THis is my code
我在 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;
}
采纳答案by Despertar
What framework are you using (Looks like the older WCf Web Api) to build your RESTful service? I would highly recommend using Microsofts new MVC4 Web API. It is really starting to mature and greatly simplifies building RESTful services. It is what is going to be supported in the future where the WCF Web API is about to be discontinued.
您使用什么框架(看起来像旧的 WCf Web Api)来构建您的 RESTful 服务?我强烈推荐使用微软新的 MVC4 Web API。它真的开始成熟并大大简化了构建 RESTful 服务。将来 WCF Web API 即将停止使用时,将支持它。
You simply return your ModelClass as a return type and it will automatically serialize it into XML or JSON depending on the requests accept header. You avoid having writing duplicate code and your service will support a wide range of clients.
您只需将 ModelClass 作为返回类型返回,它就会根据请求接受标头自动将其序列化为 XML 或 JSON。您避免编写重复的代码,您的服务将支持广泛的客户。
public class TwitterController : ApiController
{
DataScrapperApi api = new DataScrapperApi();
TwitterAndKloutData data = api.GetTwitterAndKloutData(screenName);
return data;
}
public class TwitterAndKloutData
{
// implement properties here
}
Links
链接
You can get MVC4 Web Api by downloading just MVC4 2012 RC or you can download the whole Visual Studio 2012 RC.
您可以通过仅下载 MVC4 2012 RC 或下载整个 Visual Studio 2012 RC 来获取 MVC4 Web Api。
MVC 4: http://www.asp.net/mvc/mvc4
MVC 4:http: //www.asp.net/mvc/mvc4
VS 2012: http://www.microsoft.com/visualstudio/11/en-us/downloads
VS 2012:http: //www.microsoft.com/visualstudio/11/en-us/downloads
For the original wcf web api give this a shot. Examine the accept header and generate your response according to its value.
对于原始的 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;
You would set the accept header on whatever client is initiated the request. This will differ depending on what type of client you are using to send the request but any http client will have a way to add headers.
您可以在发起请求的任何客户端上设置接受标头。这将根据您用于发送请求的客户端类型而有所不同,但任何 http 客户端都可以添加标头。
WebClient client = new WebClient();
client.Headers.Add("accept", "text/xml");
client.DownloadString("domain.com/service");
To access the response headers you would use
要访问您将使用的响应标头
WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
Additional resources: http://dotnet.dzone.com/articles/wcf-rest-xml-json-or-both
其他资源:http: //dotnet.dzone.com/articles/wcf-rest-xml-json-or-both
回答by Misha
Can you create two overloads for your method like this:
您能否像这样为您的方法创建两个重载:
[WebInvoke(UriTemplate = "dostuff", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public StuffResponse DoStuff(RequestStuff requestStuff)
[WebInvoke(UriTemplate = "dostuff", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
public StuffResponse DoStuff(RequestStuff requestStuff)
回答by muruge
You have specified the RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xmlin your WebInvokeattribute which restricts the format of both Request and Response to Xml. Remove the RequestFormat and ResponseFormatproperties and let the framework work on it based on Http headers. Content-typeheader specifies the request body type and Acceptheader specifies the response body type.
您已RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml在您的WebInvoke属性中指定了 ,该属性将请求和响应的格式限制为 Xml。删除 RequestFormat 和 ResponseFormat属性,让框架根据 Http 标头对其进行处理。Content-type标头指定请求正文类型,Accept标头指定响应正文类型。
Edit:
编辑:
This is how you would send your requests using fiddler.
这就是您使用 fiddler 发送请求的方式。


You could use Microsoft.Httpand Microsoft.Http.Extensionsdlls that comes with the REST starter kitfor writing client side code. Below is a sample.
您可以使用REST 入门工具包附带的Microsoft.Http和Microsoft.Http.Extensionsdll 来编写客户端代码。下面是一个示例。
var client = new HttpClient("http://localhost:38477/social");
client.DefaultHeaders.Accept.AddString("application/xml");
client.DefaultHeaders.ContentType = "application/xml";
HttpResponseMessage responseMessage = client.Get("twitter_name");
var deserializedContent = responseMessage.Content.ReadAsDataContract<YourTypeHere>();

