WCF REST 无法解析请求正文

标签 wcf wcf-rest

我在使用 WCF REST 解析请求正文时遇到了困难。 我的问题:

  • POST 方法 https://{Service}/X/Y? Z=0000000
  • 正文请求:{"id":"id"}

我的代码:

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST",
                BodyStyle = WebMessageBodyStyle.Bare,
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json,
                UriTemplate = "/X/{y}?Z={z}")
                ]
    string GetRequest(string y, string z, Request request);
}
public class Service : IService
{
    public string GetRequest(string y, string z, Request request)
    {
        //Do sth
    }


[DataContract]
public class Request
{
    [DataMember]
    [JsonProperty("id")]
    public String  Id { get; set; }
}

我遇到的问题是 y 和 z 有数据并且它们是正确的,但是请求中的 id 为空。我希望是“id”。

我在互联网上搜索了很多,发现 Stream 解决方案在这种情况下不容易遵循。 我想知道是否有人有一个聪明的主意来做到这一点。

最佳答案

看看这个版本

服务

namespace ServiceTest
{
    internal class Program
    {
        private static WebServiceHost _service;

        private static void Main()
        {
            _service = new WebServiceHost(typeof (Service));
            Console.WriteLine("The service has started");
            _service.Open();
            Console.ReadKey();
        }
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public sealed class Service : IService
    {
        public string GetRequest(string y, string z, Request request)
        {
            Console.WriteLine("Y: {0}, Z: {1}, request: {2}", y, z, request);
            return "Ok";
        }
    }

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json, UriTemplate = "/X/{y}?Z={z}")]
        string GetRequest(string y, string z, Request request);
    }

    [DataContract]
    public sealed class Request
    {
        [DataMember]
        public string Id { get; set; }

        public override string ToString()
        {
            return string.Format("Id: {0}", Id);
        }
    }
}

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

    <system.serviceModel>
        <services>
            <service name="ServiceTest.Service">
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:9090/webhost" />
                    </baseAddresses>
                </host>
                <endpoint binding="webHttpBinding" contract="ServiceTest.IService" />
            </service>
        </services>
    </system.serviceModel>

    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

客户

internal class Program
{
    private static void Main(string[] args)
    {
        var client = new HttpClient();
        var request = new Request {Id = "Nelibur"};
        var result = client.PostAsync("http://localhost:9090/webhost/X/Y?Z=2000", CreateContent(request)).Result;
        Console.WriteLine(result.Content.ReadAsStringAsync().Result);
        Console.ReadKey();
    }

    private static StringContent CreateContent<T>(T value)
    {
        using (var stream = new MemoryStream())
        {
            var serializer = new DataContractJsonSerializer(typeof (T));
            serializer.WriteObject(stream, value);
            string content = Encoding.UTF8.GetString(stream.ToArray());
            return new StringContent(content, Encoding.UTF8, "application/json");
        }
    }
}

原始请求:

POST http://localhost:9090/webhost/X/Y?Z=2000 HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: localhost:9090
Content-Length: 16
Expect: 100-continue
Connection: Keep-Alive

{"Id":"Nelibur"}

您可以尝试使用例如 Fiddler 中的请求

关于WCF REST 无法解析请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23289727/

相关文章:

c# - IDispatchMessageInspector : Improving BeforeSendReply functionality

wcf - 为什么在 ASP.NET MVC 中有 JsonResult 时使用 WCF REST?

WCF REST 错误 HTTP 307

json - 无法在 jQuery.ajax 中将内容类型设置为 'application/json'

c# - 使用 linq 时从 WCF 服务返回什么?

java - C# 和 Java - 将文件从 Android 上传到 WCF

xml - 我应该在 WCF 之前学习 XML 吗?

wcf - WCF 服务的 Win32Exception @ ServiceHost.Open()

wcf - WCF REST Starter Kit 是否不再是创建 Restful 服务的最佳方式?

c# - RequestInterceptor 和 MessageInspector 有什么区别?