简体   繁体   English

在C#中将HTTP Accept和Content-Type标头设置为“application / xml”

[英]set both the HTTP Accept and Content-Type headers to “application/xml” in C#

I created a web service (REST) in C#. 我在C#中创建了一个Web服务(REST)。 Now I want that when someone uses it, it should return JSON or XML as per Header. 现在我希望当有人使用它时,它应该按照Header返回JSON或XML。 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 . 我跟着它,但我不知道它在哪里set both the HTTP Accept and Content-Type headers to "application/xml" ,我以这种方式调用它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 如果我的问题不是很清楚,我可以回答任何问题,谢谢,这是我的代码

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

        }

What framework are you using (Looks like the older WCf Web Api) to build your RESTful service? 你使用什么框架(看起来像旧的WCf Web Api)来构建你的RESTful服务? I would highly recommend using Microsofts new MVC4 Web API. 我强烈建议使用Microsofts新的MVC4 Web API。 It is really starting to mature and greatly simplifies building RESTful services. 它真正开始成熟并大大简化了构建RESTful服务。 It is what is going to be supported in the future where the WCF Web API is about to be discontinued. 它将在未来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. 您只需将ModelClass作为返回类型返回,它将根据请求接受标头自动将其序列化为XML或JSON。 You avoid having writing duplicate code and your service will support a wide range of clients. 您可以避免编写重复的代码,并且您的服务将支持广泛的客户端。

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获得MVC4 Web Api,也可以下载整个Visual Studio 2012 RC。

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. 对于原始的wcf web api,请试一试。 Examine the accept header and generate your response according to its value. 检查接受标头并根据其值生成响应。

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

You have specified the RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml in your WebInvoke attribute which restricts the format of both Request and Response to Xml. 您已在WebInvoke属性中指定了RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.XmlWebInvoke Request和Response的格式限制为Xml。 Remove the RequestFormat and ResponseFormat properties and let the framework work on it based on Http headers. 删除RequestFormat和ResponseFormat属性,让框架基于Http头进行处理。 Content-type header specifies the request body type and Accept header specifies the response body type. Content-type标头指定请求主体类型, Accept标头指定响应主体类型。

Edit: 编辑:

This is how you would send your requests using fiddler. 这是您使用fiddler发送请求的方式。

在此输入图像描述

You could use Microsoft.Http and Microsoft.Http.Extensions dlls that comes with the REST starter kit for writing client side code. 您可以使用REST入门工具包附带的Microsoft.HttpMicrosoft.Http.Extensions dll来编写客户端代码。 Below is a sample. 以下是一个示例。

        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>();

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Owin / WebApi强制仅接受application / json Accept和Content-Type标头 - Owin/WebApi force to to accept only application/json Accept and Content-Type headers 如何在C#4.0中读取内容类型为application / json的HTTP Post数据 - How to read HTTP Post data with content-type of application/json in C# 4.0 C#:在HTTP中使用Content-Type标头发送参数 - C#: Sending parameter with Content-Type Header in HTTP 如何在 c# 中将 Google.Cloud.Tasks.V2 HttpRequest 的 Content-Type 设置为“application/json”? - How to set the Content-Type to "application/json" for Google.Cloud.Tasks.V2 HttpRequest in c#? 从 Azure App Configuration Store 获取 Value,其中 content-type 在 C# 中设置为 application/json - Get Value from Azure App Configuration Store where the content-type is set to application/json in C# C# HttpRequestMessage Content-Type 强制为“application/json” - C# HttpRequestMessage Content-Type force as "application/json" only 如何在C#中检查内容类型/应用程序文本 - how to check content-type/application text in c# c# HttpClient post response content-type application/json - c# HttpClient post response content-type application/json 更改WCF服务以接受内容类型“ application / xml; charset = utf-8” - Change WCF service to accept content-type “application/xml;charset=utf-8” 使用内容类型application / x-www-form-urlencoded解析从HTTP POST接收的C#中的JSON数据 - Parsing JSON data in C# received from HTTP POST with content-type application/x-www-form-urlencoded
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM