C# 如何通过JSON请求从fiddler调用wcf restful服务?

C# 如何通过JSON请求从fiddler调用wcf restful服务?,c#,wcf,json,fiddler,C#,Wcf,Json,Fiddler,我是wcf restful服务的新手。我找不到问题,那就是为什么我的wcf restful服务给出了“坏请求”。我使用.NET4.0 我的服务是: [OperationContract(Name="Add")] [WebInvoke(UriTemplate = "test/", Method = "POST", ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json

我是wcf restful服务的新手。我找不到问题,那就是为什么我的wcf restful服务给出了“坏请求”。我使用.NET4.0

我的服务是:

[OperationContract(Name="Add")]
[WebInvoke(UriTemplate = "test/", Method = "POST",
          ResponseFormat=WebMessageFormat.Json,
          RequestFormat=WebMessageFormat.Json )]
public int Add(Number n1)
{
    res = Convert.ToInt32(n1.Number1) + Convert.ToInt32(n1.Number2);
    return res;
}
User-Agent: Fiddler
Host: localhost:4217
Content-Type: application/json; charset=utf-8
{"Number1":"7","Number2":"7"}
HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 14 Aug 2011 18:10:21 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 5450
Cache-Control: private
Content-Type: text/html
Connection: Close
uri = "http://localhost:4217/Service1.svc/";
Number obj = new Number() { Number1 = 7, Number2 = 7 };
using (HttpResponseMessage response = new HttpClient().Post(uri+"test/",
       HttpContentExtensions.CreateDataContract(obj)))
{
    string res = response.Content.ReadAsString();
    return res.ToString();
}
数据是..

[Serializable]
    public class Number
    {
        public int Number1 { get; set; }
        public int Number2 { get; set; }
    }
当我从fiddler调用它时,返回“HTTP/1.1400错误请求”

我的fiddler请求头是:

[OperationContract(Name="Add")]
[WebInvoke(UriTemplate = "test/", Method = "POST",
          ResponseFormat=WebMessageFormat.Json,
          RequestFormat=WebMessageFormat.Json )]
public int Add(Number n1)
{
    res = Convert.ToInt32(n1.Number1) + Convert.ToInt32(n1.Number2);
    return res;
}
User-Agent: Fiddler
Host: localhost:4217
Content-Type: application/json; charset=utf-8
{"Number1":"7","Number2":"7"}
HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 14 Aug 2011 18:10:21 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 5450
Cache-Control: private
Content-Type: text/html
Connection: Close
uri = "http://localhost:4217/Service1.svc/";
Number obj = new Number() { Number1 = 7, Number2 = 7 };
using (HttpResponseMessage response = new HttpClient().Post(uri+"test/",
       HttpContentExtensions.CreateDataContract(obj)))
{
    string res = response.Content.ReadAsString();
    return res.ToString();
}
请求主体为:

[OperationContract(Name="Add")]
[WebInvoke(UriTemplate = "test/", Method = "POST",
          ResponseFormat=WebMessageFormat.Json,
          RequestFormat=WebMessageFormat.Json )]
public int Add(Number n1)
{
    res = Convert.ToInt32(n1.Number1) + Convert.ToInt32(n1.Number2);
    return res;
}
User-Agent: Fiddler
Host: localhost:4217
Content-Type: application/json; charset=utf-8
{"Number1":"7","Number2":"7"}
HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 14 Aug 2011 18:10:21 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 5450
Cache-Control: private
Content-Type: text/html
Connection: Close
uri = "http://localhost:4217/Service1.svc/";
Number obj = new Number() { Number1 = 7, Number2 = 7 };
using (HttpResponseMessage response = new HttpClient().Post(uri+"test/",
       HttpContentExtensions.CreateDataContract(obj)))
{
    string res = response.Content.ReadAsString();
    return res.ToString();
}
而响应标题为:

[OperationContract(Name="Add")]
[WebInvoke(UriTemplate = "test/", Method = "POST",
          ResponseFormat=WebMessageFormat.Json,
          RequestFormat=WebMessageFormat.Json )]
public int Add(Number n1)
{
    res = Convert.ToInt32(n1.Number1) + Convert.ToInt32(n1.Number2);
    return res;
}
User-Agent: Fiddler
Host: localhost:4217
Content-Type: application/json; charset=utf-8
{"Number1":"7","Number2":"7"}
HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 14 Aug 2011 18:10:21 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 5450
Cache-Control: private
Content-Type: text/html
Connection: Close
uri = "http://localhost:4217/Service1.svc/";
Number obj = new Number() { Number1 = 7, Number2 = 7 };
using (HttpResponseMessage response = new HttpClient().Post(uri+"test/",
       HttpContentExtensions.CreateDataContract(obj)))
{
    string res = response.Content.ReadAsString();
    return res.ToString();
}
但是,如果我通过C#客户机程序调用此服务,就可以了

我的客户代码是:

[OperationContract(Name="Add")]
[WebInvoke(UriTemplate = "test/", Method = "POST",
          ResponseFormat=WebMessageFormat.Json,
          RequestFormat=WebMessageFormat.Json )]
public int Add(Number n1)
{
    res = Convert.ToInt32(n1.Number1) + Convert.ToInt32(n1.Number2);
    return res;
}
User-Agent: Fiddler
Host: localhost:4217
Content-Type: application/json; charset=utf-8
{"Number1":"7","Number2":"7"}
HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 14 Aug 2011 18:10:21 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 5450
Cache-Control: private
Content-Type: text/html
Connection: Close
uri = "http://localhost:4217/Service1.svc/";
Number obj = new Number() { Number1 = 7, Number2 = 7 };
using (HttpResponseMessage response = new HttpClient().Post(uri+"test/",
       HttpContentExtensions.CreateDataContract(obj)))
{
    string res = response.Content.ReadAsString();
    return res.ToString();
}
请帮帮我


谢谢

您做错的一件事是请求对象的格式。将其更改为:

{ n1: { "Number1":"7","Number2":"7"} }
参数名称是传递给wcf json端点的json对象的根属性名称

我有一个关于git的问题。除此之外,它还有一个json端点,在我的示例中,我使用jquery调用它。我建议您构建一个类似的网页(将其托管在与WCF服务相同的网站上),通过jquery调用json服务,并在fiddler运行时测试该服务,以获取示例请求。这将比自己构造请求更容易,更不容易出错,因为jquery将处理头中的大量细节

调用my echo服务的示例jquery ajax代码如下所示,您可以根据自己的服务进行调整:

    $("#btnEchoString").click(function () {
        var request = $("#request");
        var response = $("#response");
        $.ajax({
            url: 'EchoService.svc/JSON/Echo',
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ request: request.val() }),
            dataType: "json",
            success: function (data) {
                response.val(data.d);
            },
            error: function (request, status, error) {
                //TODO: do something here
            }
        });
    });

找出代码问题的方法是在服务器上运行,它会有一个解释问题的异常。我用您的代码编写了一个简单的测试,它有一个类似的错误(400),并且跟踪有以下错误:

The data contract type 'WcfForums.StackOverflow_7058942+Number' cannot be
deserialized because the required data members '<Number1>k__BackingField,
<Number2>k__BackingField' were not found.
[Serializable]
标记的数据类型序列化对象中的所有字段,而不是属性。通过注释该属性,代码实际上运行得很好(该类型属于“POCO”(普通旧Clr对象)规则,该规则序列化所有公共字段和属性

public class StackOverflow_7058942
{
    //[Serializable]
    public class Number
    {
        public int Number1 { get; set; }
        public int Number2 { get; set; }
    }
    [ServiceContract]
    public class Service
    {
        [OperationContract(Name = "Add")]
        [WebInvoke(UriTemplate = "test/", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        public int Add(Number n1)
        {
            int res = Convert.ToInt32(n1.Number1) + Convert.ToInt32(n1.Number2);
            return res;
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(Service), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
        host.Open();
        Console.WriteLine("Host opened");

        WebClient c = new WebClient();
        c.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
        c.Encoding = Encoding.UTF8;
        Console.WriteLine(c.UploadString(baseAddress + "/test/", "{\"Number1\":\"7\",\"Number2\":\"7\"}"));

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}
WCF REST的“正常”用法是使用
行为(或
WebHttpBehavior
,如果是通过代码),而不是示例中的
。例如,默认的BodyStyle是
Bare
,这意味着不需要使用参数名将对象包装在JSON对象中(默认为
WrappedRequest
)。