小编典典

如何在WCF DataService中接受JSON?

json

我试图了解如何使用WCF数据服务(基于EF 4.1)创建一个宁静的Web服务,该服务将保留作为JSON对象传递的实体。

我已经能够创建一种方法,该方法可以接受以一组原始数据类型作为参数的GET请求。我不喜欢这种解决方案,我更喜欢在HTTP请求正文中发送带有JSON对象的POST请求。

我发现我无法获得将json序列化为对象的框架,但是我可以手动完成。

我的问题是我似乎无法读取POST请求的主体-主体应该是JSON有效负载。

下面是一个粗糙的裂缝。我尝试了一些不同的迭代,但似乎无法从请求正文中获取原始JSON。

有什么想法吗?更好的方法呢?我只想发布一些JSON数据并进行处理。

    [WebInvoke(Method = "POST")]
    public void SaveMyObj()
    {
        StreamReader r = new StreamReader(HttpContext.Current.Request.InputStream);
        string jsonBody = r.ReadToEnd();  // jsonBody is empty!!

        JavaScriptSerializer jss = new JavaScriptSerializer();
        MyObj o = (MyObj)jss.Deserialize(jsonBody, typeof(MyObj));

        // Now do validation, business logic, and persist my object
    }

我的数据服务是一个扩展的实体框架数据服务

System.Data.Services.DataService<T>

如果尝试将非原始值作为方法的参数添加,则在跟踪日志中会看到以下异常:

System.InvalidOperationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'Void SaveMyObj(MyNamespace.MyObj)' has a parameter 'MyNamespace.MyObj o' of type 'MyNamespace.MyObj' which is not supported for service operations. Only primitive types are supported as parameters.

阅读 278

收藏
2020-07-27

共1个答案

小编典典

将参数添加到您的方法。您还需要WebInvoke上的一些其他属性。

这是一个示例(从内存来看,可能会有些偏离)

[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "modifyMyPerson")]
public void Modify(Person person) {
   ...
}

对于人员类,如下所示:

[DataContract]
public class Person {

[DataMember(Order = 0)]
public string FirstName { get; set; }

}

和json这样发送

var person = {FirstName: "Anthony"};
var jsonString = JSON.stringify({person: person});
// Then send this string in post using whatever, I personally use jQuery

编辑:这是使用“包装”的方法。如果没有包装方法,您将取出BodyStyle = ...并对其进行字符串化,就可以了JSON.stringify(person)。如果需要添加其他参数,我通常只使用包装方法。

编辑完整代码示例

Global.asax

using System;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Routing;

namespace MyNamespace
{
    public class Global : HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.Add(new ServiceRoute("myservice", new WebServiceHostFactory(), typeof(MyService)));
        }
    }
}

Service.cs

using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace MyNamespace
{
    [ServiceContract]
    [ServiceBehavior(MaxItemsInObjectGraph = int.MaxValue)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MyService
    {
        [OperationContract]
        [WebInvoke(UriTemplate = "addObject", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public void AddObject(MyObject myObject)
        {
            // ...
        }

        [OperationContract]
        [WebInvoke(UriTemplate = "updateObject", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public void UpdateObject(MyObject myObject)
        {
            // ...
        }

        [OperationContract]
        [WebInvoke(UriTemplate = "deleteObject", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public void DeleteObject(Guid myObjectId)
        {
            // ...
        }
    }
}

并将其添加到 Web.config

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>
2020-07-27