发送json到wcf服务 [英] send json to wcf service
问题描述
好吧,我已经为此工作了几天,现在开始让我烦恼.
OK I have been working on this for a few days now an it is starting to annoy me.
我有一个页面,用户可以在其中更改配色方案.然后为页面选择徽标.
I have a page where the user can change the colour scheme. And choose a logo for the page.
使用jquery循环所有可以更改的项目($(.brand").each)
Using jquery to loop round all the items that can be changed ($(".brand").each)
构建数据,最后将其作为json对象发送到wcf服务,请参见
and build up the data and finally send it to a wcf service as a json object, see below
$(".brand").each(function () {
//use the title attribute to list the css properties
// you want for that element
//use the id with a prefix to represent the actual element
// you want to brand,
//matching up with the item in the site's css
//prefix 'c-' = css class so replace with '.'
//prefix 'id-' = element id so replace with '#'
//prefix 'e-' = element so just remove the prefix
var id = $(this).attr("id").replace("c-", ".").replace("id-", "#").replace("e-", "");
var title = $(this).attr("title");
var values = title.split(',');
var property = "";
var value = "";
for (var i = 0; i < values.length; i++) {
selector = values[i]
value = $(this).css(values[i]);
}
var item = {};
item["id"] = "";
item["selector"] = id;
item["css_property"] = property;
item["property_value"] = value;
json.push(item);
});
if ($(".imgbase").val().length > 0) {
var logoUrl = $(".imgbase").val();
logoUrl = logoUrl.replace(new RegExp("^data:image/[a-z]*;base64,", ""));
var item = {};
item["id"] = 1;
item["selector"] = "";
item["css_property"] = "";
item["property_value"] = logoUrl;
json.push(item);
}
$.ajax({
type: "POST",
contentType: "application/json",
url: "http://localhost:64177/BrandingService.svc/DoBranding",
data: JSON.stringify({ CSS: json }),
dataType: "json",
success: function (msg) {
if (msg.hasOwnProperty("d"))
alert(msg.d);
},
error: function (result) {
alert("Failed to call service: (" + result.status + ") \n" + result.statusText);
}
});
现在这似乎创建了一个数组对象,所以我的问题是,我的服务到底应该期待什么,以及如何阅读?假设我发送正确吗?如果我将其作为对象接收,则没有错误,但是服务不知道它是什么,并且不能反序列化它.我无法将其作为List(Of BrandingCSS)接收,这会导致500错误,我有一个类(请参阅底部),我试图用作List(Of BrandingCSS),所以如何获得"CSS对象"到那?我已经尝试过JavaScriptSerializer和Json.net,我愿意接受其中任何一个来取得结果,因此,如果有人可以提供帮助,请在我发疯之前进行.
Now this seems to create an array object, so my question is, what on earth should my service be expecting, and how do I read it? Assuming I am sending it correctly? If I receive it as an object there is no error but the service has no idea what it is and cannot deserialize it. I can't receive it as a List(Of BrandingCSS), this causes a 500 error, I have a class (see bottom), That I am trying to use as a List(Of BrandingCSS), so how do I get the "CSS Object" into that? I have tried the JavaScriptSerializer and Json.net, I am open to either to get a result, so if anyone can help, please do before I go insane.
<OperationContract()>
Public Function DoBranding(ByVal CSS As Object) As String
Try
Return "FOO"
Catch ex As Exception
Return "BAR: " & ex.Message
End Try
End Function
我正在使用的班级
<DataContract([Namespace]:="")> _
Public Class BrandingCSS
<DataMember>
Public Property ServiceID() As Integer
Get
Return m_ServiceID
End Get
Set(value As Integer)
m_ServiceID = value
End Set
End Property
Private m_ServiceID As Integer
<DataMember>
Public Property selector() As String
Get
Return m_selector
End Get
Set(value As String)
m_selector = value
End Set
End Property
Private m_selector As String
<DataMember>
Public Property css_property() As String
Get
Return m_property
End Get
Set(value As String)
m_property = value
End Set
End Property
Private m_property As String
<DataMember>
Public Property property_value() As String
Get
Return m_value
End Get
Set(value As String)
m_value = value
End Set
End Property
Private m_value As String
<DataMember>
Public ReadOnly Property logo() As Byte()
Get
Return img
End Get
End Property
Private img As Byte() = Nothing
Public Sub New()
Try
img = Convert.FromBase64String(property_value)
Catch ex As Exception
img = Nothing
End Try
End Sub
End Class
如果您想在web.config中看到服务"部分,就是这个
If you are wanting to see the services section in the web.config it is this
<system.serviceModel>
<services>
<service name="BrandingService">
<endpoint address="" behaviorConfiguration="BrandingServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="BrandingService" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="BrandingServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="5000000" />
</webServices>
</scripting>
</system.web.extensions>
和发送的json示例在这里
and a sample of the json sent is here
"[
{\"id\":\"1\",\"selector\":\".mp-level\",\"css_property\":\"background\",\"property_value\":\"\"},
{\"id\":\"1\",\"selector\":\".mp-level\",\"css_property\":\"color\",\"property_value\":\"\"},
{\"id\":\"1\",\"selector\":\"#header\",\"css_property\":\"background\",\"property_value\":\"\"},
{\"id\":\"1\",\"selector\":\"#header\",\"css_property\":\"color\",\"property_value\":\"\"},
{\"id\":\"1\",\"selector\":\"#header\",\"css_property\":\"border-bottom-color\",\"property_value\":\"\"},
{\"id\":\"1\",\"selector\":\"headerinput\",\"css_property\":\"background\",\"property_value\":\"\"},
{\"id\":\"1\",\"selector\":\"headerbutton\",\"css_property\":\"background\",\"property_value\":\"\"},
{\"id\":\"1\",\"selector\":\"footer\",\"css_property\":\"background\",\"property_value\":\"\"},
{\"id\":\"1\",\"selector\":\"footer\",\"css_property\":\"color\",\"property_value\":\"\"}
]"
推荐答案
首先,添加
contentType: "application/json;charset=utf-8"
在您的POST请求标头中.
in your POST request header.
在您的服务合同中我没有看到RequestFormat = WebMessageFormat.Json
.
I haven't seen RequestFormat = WebMessageFormat.Json
in your service contract.
C#代码
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "CSSBranding",
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
string DoBranding(BrandingCSS[] css);
请注意,您的JSON和 BrandingCSS 类应具有相同的参数.例如,对于JSON中的选择器",您必须在 BrandingCSS 类中具有"选择器"属性.
Note that your JSON and BrandingCSS class should have same parameters. For example, for "selector" in JSON, you must have "selector" property in BrandingCSS class.
[DataContract(Namespace = "")]
public class BrandingCSS
{
[DataMember]
public string selector {get; set;}
[DataMember]
public string id {get; set;}
//Remaining properties here.
}
希望您能理解 C#代码.
编辑 如果要检查服务应接受的JSON,请为 BrandingCSS 类重写 ToString()方法.
EDIT If you want to check what JSON your service should accept, override the ToString() method for your BrandingCSS class.
public override string ToString()
{
JavaScriptSerializer js = new JavaScriptSerializer(); // Available in System.Web.Script.Serialization;
return js.Serialize(this);
}
现在创建一个 BrandingCSS 类的对象.
Now make an object of class BrandingCSS.
BrandingCSS bcss = new BrandingCSS();
string acceptedJson = bcss.ToString();
Console.WriteLine(acceptedJson);
或者您可以临时创建OperationContract并调用以下代码行.在此处找到一个断点,然后查看JSON.之后,制作一个您刚刚在调试器中看到的JSON并发送请求.请参阅 500内部服务器错误..而且您也没有显示您的 Web.Config 文件.
or you can make a temp OperationContract and call these line of codes. Hit a break point there and see the JSON. After that, make a JSON that you just have seen in debugger and send request. See 500 Internal Server Error.. And also you haven't shown your Web.Config file.
这篇关于发送json到wcf服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!