5

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

我已经能够创建一个可以接受带有一组原始数据类型作为参数的 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
    }

我的 DataService 是一个实体框架 DataService,它扩展

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.
4

1 回答 1

8

将参数添加到您的方法。您还需要 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 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>
于 2011-08-02T21:14:20.567 回答