WCF 与 ASP.NET 网络 API

WCF with ASP.NET Web API

我有一个 WCF 服务需要支持 JSON 的 HTTP 请求,但默认的序列化程序 (DataContractSerializer) 不能很好地完成这项工作。我读到 Web API 是这些天要走的路,但我遇到的所有示例都需要使用模型并且只能使用简单的 CRUD 操作。我的 WCF 服务执行的不仅仅是 CRUD 操作。它还 accepts/returns 数据类型,如字典列表。关于我应该如何处理这个问题有什么建议吗?

...the default serializer (DataContractSerializer) just doesn't do the job very well

DataContractJsonSerializer 有什么不好做的?我没有遇到任何问题。无论如何,如果您想将其换成 JSON.net,请参阅操作说明 here and here

I read about Web API is the way to go these days

好吧,这是有争议的。如果您只想要一个 HTTP api,那么像 Nancy 这样的平台比 WebAPI 更容易使用。但是您通常是正确的,WebApi 优于 WCF webHttpBinding。

...only work with simple CRUD operations. My WCF service performs more than CRUD operations

这是不正确的,WebAPI 可以以更 RPC 风格的方式使用。例如,您可以这样做:

[AcceptVerbs("POST")]
public HttpResponseMessage DoSomeAction(Something actionParams)
{
    ...

    return new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent("Action done")
    };
}

只是这种违背了REST原则,所以你看到的样本一般不会包含这种服务操作。

至于推荐的方法,我的优先顺序是:

  • Nancy 作为首选,托管在 windows 服务中
  • 如果有 IIS 托管要求,WebApi
  • WebHttpBinding 如果没有 IIS 要求并且您已经大量投资于 WCF