OK Я работаю над этим в течение нескольких дней, и это начинает раздражать меня.отправить json в службу wcf
У меня есть страница, на которой пользователь может изменить цветовую схему. И выберите логотип для страницы.
Использование JQuery для цикла объехать все те элементы, которые могут быть изменены ($ («бренд»). Каждый)
и создать данные и, наконец, отправить его на службу ФОС в качестве объекта JSon см ниже
$(".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);
}
});
Теперь это, кажется, создает объект массива, поэтому мой вопрос, что на земле моей служба должна ожидать, и как я могу читать? Предполагаю, что я правильно его отправляю? Если я получаю его как объект, ошибки нет, но служба не знает, что это такое и не может десериализовать его. Я не могу получить его как Список (BrandingCSS), это вызывает ошибку 500, у меня есть класс (см. Ниже), который я пытаюсь использовать в качестве списка (BrandingCSS), так как я могу получить " CSS Object "? Я пробовал JavaScriptSerializer и Json.net, я открыт для получения результата, поэтому, если кто-то может помочь, сделайте, прежде чем я сойду с ума.
<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 именно это
<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 послали здесь
"[
{\"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\":\"\"}
]"
Это сервис RESTFull? –
Это сервис WCF на самом веб-сайте, я попробовал RESTFull-сервис как отдельный проект за его пределами, и это дало те же результаты. –