Access Request Body in a WCF RESTful Service

前端 未结 7 1040
不思量自难忘°
不思量自难忘° 2020-12-31 03:14

How do I access the HTTP POST request body in a WCF REST service?

Here is the service definition:

[ServiceContract]
public interface ITestService
{
          


        
7条回答
  •  渐次进展
    2020-12-31 03:38

    Here is what I did:

    using System.IO;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System;
    using System.IO;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Web;
    using System.Text;
    
    namespace YourSpaceName
    {
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
        public class YourClassName
        {
            [OperationContract]
            [WebInvoke(Method = "POST", UriTemplate = "YourMethodName({id})", BodyStyle = WebMessageBodyStyle.Bare)]
            public Stream YourMethodName(Stream input, string id)
            {
                WebOperationContext ctx = WebOperationContext.Current;
                ctx.OutgoingResponse.Headers.Add("Content-Type", "application/json");
    
                string response = $@"{{""status"": ""failure"", ""message"": ""Please specify the Id of the vehicle requisition to retrieve."", ""d"":null}}";
                try
                {
                    string response = (new StreamReader(input)).ReadToEnd();
                }
                catch (Exception ecp)
                {
                    response = $@"{{""status"": ""failure"", ""message"": ""{ecp.Message}"", ""d"":null}}";
                }
    
                return new MemoryStream(Encoding.UTF8.GetBytes(response));
            }
        }
    }
    

    This code simply reads the input and writes it out. the body of the POST request is automatically assigned to input irrespect of the variable name. As you can see, you can still have variables in your your UriTemplate.

提交回复
热议问题