Passing JSON data to WCF (.Net 4) Web Service
I have a very simple [OperationContract] called TestClass that gets called like this:
var person = { "Name": "Dave", "City":"HB", "State": "CA", "Zip":"92649" };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(person),
url: "MyService.svc/TestClass",
success: function (data) {
$("#output").text("[ " + data + "]");
}
});
What I'm not understanding, and can't seem to find, is the preferred way of using these services. I've been searching everywhere for the past few days and I feel really overwhelmed with what I've found so far. 开发者_Go百科I read one post where somebody said not to use Message but to create their own DataContract which I tried.
Here is my Operation Contract:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public Message TestClass(Message m)
{ return WebOperationContext.Current.CreateTextResponse(JsonConvert.SerializeObject("Ok"));}
Besides having 4 input values to TestClass, I would prefer just one. Message is the only thing that seems to work. I tried using just a string and that value is always null.
I've tried creating a [DataContract] for the data and use that as the parameter in the TestClass call but that also is null.
I'm new to using these service types so any pointers for a beginner is greatly appreciated.
Thank you in advance.
UPDATE
IService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfTest
{
[System.ServiceModel.ServiceContractAttribute()]
public interface IService
{
[System.ServiceModel.Web.WebInvokeAttribute(BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Bare,
RequestFormat = System.ServiceModel.Web.WebMessageFormat.Json,
ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
[System.ServiceModel.OperationContractAttribute()]
void ProcessData(RootClass input);
}
[System.Runtime.Serialization.DataContractAttribute()]
public partial class RootClass
{
[System.Runtime.Serialization.DataMemberAttribute()]
public string Name;
[System.Runtime.Serialization.DataMemberAttribute()]
public string City;
[System.Runtime.Serialization.DataMemberAttribute()]
public string State;
[System.Runtime.Serialization.DataMemberAttribute()]
public string Zip;
}
}
ServiceZ.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Newtonsoft.Json;
namespace WcfTest
{
public class ServiceZ : IService
{
public void ProcessData(RootClass input)
{
int i = 6; // used for a breakpoint
}
}
}
Index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function () {
var person = { "Name": "Dave", "City": "HB", "State": "CA", "Zip": "92649" };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(person),
url: "ServiceZ.svc/ProcessData",
success: function (data) {
$("#output").text("OK!");
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
}
});
});
</script>
</head>
<body>
<div id="output" style="background: lightgreen;">--></div>
</body>
You can use a the data contract for your data. The tool at http://carlosfigueira.me/JsonUtilities/JsonToContract.htm (more information about it at http://blogs.msdn.com/b/carlosfigueira/archive/2011/01/11/inferring-schemas-for-json.aspx) can give you a data contract which is compatible with the JSON data. By running it with your input I got the code below.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:v4.0.30319
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[System.ServiceModel.ServiceContractAttribute()]
public interface IService
{
[System.ServiceModel.Web.WebInvokeAttribute(BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Bare, RequestFormat = System.ServiceModel.Web.WebMessageFormat.Json, ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
[System.ServiceModel.OperationContractAttribute()]
void ProcessData(RootClass input);
}
[System.Runtime.Serialization.DataContractAttribute()]
public partial class RootClass
{
[System.Runtime.Serialization.DataMemberAttribute()]
public string Name;
[System.Runtime.Serialization.DataMemberAttribute()]
public string City;
[System.Runtime.Serialization.DataMemberAttribute()]
public string State;
[System.Runtime.Serialization.DataMemberAttribute()]
public string Zip;
}
Update: I created a new project (empty web application), and added the following files - the client received the correct response. Try comparing with what you have to see if there is anything different. And the 415 error you're getting usually indicates which you don't have the appropriate binding / behavior on this endpoint. To enable REST endpoints (which can accept JSON), the endpoint needs to have the webHttpBinding
and a behavior with the <webHttp/>
on it. Or another alternative (which is what I used) is to use the WebServiceHostFactory
on the .svc file, in which case you don't need anything on web.config.
ServiceZ.svc
<%@ ServiceHost Language="C#" Debug="true"
Service="StackOverflow_7141298.ServiceZ"
CodeBehind="ServiceZ.svc.cs"
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
IServiceZ.cs
namespace StackOverflow_7141298
{
[System.ServiceModel.ServiceContractAttribute()]
public interface IService
{
[System.ServiceModel.Web.WebInvokeAttribute(BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Bare, RequestFormat = System.ServiceModel.Web.WebMessageFormat.Json, ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
[System.ServiceModel.OperationContractAttribute()]
string ProcessData(RootClass input);
}
[System.Runtime.Serialization.DataContractAttribute()]
public partial class RootClass
{
[System.Runtime.Serialization.DataMemberAttribute()]
public string Name;
[System.Runtime.Serialization.DataMemberAttribute()]
public string City;
[System.Runtime.Serialization.DataMemberAttribute()]
public string State;
[System.Runtime.Serialization.DataMemberAttribute()]
public string Zip;
}
}
ServiceZ.svc.cs
namespace StackOverflow_7141298
{
public class ServiceZ : IService
{
public string ProcessData(RootClass input)
{
if (input == null) return "NULL!!!";
StringBuilder sb = new StringBuilder();
return string.Format("Name={0},City={1},State={2},Zip={3}",
input.Name ?? "<<null>>",
input.City ?? "<<null>>",
input.State ?? "<<null>>",
input.Zip ?? "<<null>>");
}
}
}
HTMLPage1.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
$().ready(function () {
var person = { "Name": "Dave", "City": "HB", "State": "CA", "Zip": "92649" };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(person),
url: "ServiceZ.svc/ProcessData",
success: function (data) {
$("#output").text(data);
},
error: function (jqXHR, textStatus, errorThrown) {
//debugger;
$("#output").text("Error!");
}
});
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
精彩评论