简体   繁体   中英

WCF REST Web Service and HTTP Headers

I've created a REST web service that returns a simply id passed in xml format.

However, as part of the xml returned, I want to include custom headers. I want to be able to read the data in the request headers and return some of them back in the response.

For example, if the request includes Header1 and Header2, I want to return Header1 and Header2 as part of the response, along with a new header, Header3.

I'm struggling to work out where and how to do this so any help would be appreciated.

My code:

RestServiceImpl.svc.cs:

namespace RestService
{
    public class RestServiceImpl : IRestServiceImpl
    {
        #region iRestService Members

        public string XMLData(string id)
        {
            return "You requested product " + id;
        }

        #endregion
    }
}

IRestServiceImpl.cs:

namespace RestService
{
    [ServiceContract]
    public interface IRestServiceImpl
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "xml/{id}")]
        string XMLData(string id);

    }
}

You can access requested header using folowing.

System.ServiceModel.Web.WebOperationContext ctx = System.ServiceModel.Web.WebOperationContext.Current;
String request_header_value1 = ctx.IncomingRequest.Headers["Incoming_Req_Header_Key1"].ToString();

Here, Incoming_Req_Header_Key1 is key of incoming header , like Incoming_Req_Header_Key1: Incoming_Req_Header_Value1 , so request_header_value1 = Incoming_Req_Header_Value1 .

In response, you can use above string and append more result such as "CustomHeader3" ( just an example from yours) to response. And if you want to append them to response header, you can do that by using ctx.OutgoingResponse.Headers .

UPDATE

I have used following code.

在此输入图像描述

Here is the output.

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM