简体   繁体   English

我可以在WebAPI上运行WCF吗?

[英]Can I run WCF on top of WebAPI?

For a work project, I'm building an application consisting of a frontend SPA (Aurelia), a WebAPI backend for that SPA, and a multitude of web service WebAPI projects contained in existing applications. 对于一个工作项目,我正在构建一个包含前端SPA(Aurelia),该SPA的WebAPI后端以及现有应用程序中包含的多个Web服务WebAPI项目的应用程序。 (This application will perform data aggregation - it's a dashboard for our clients to show relevant information from many sources.) (此应用程序将执行数据汇总-这是我们的客户用来显示来自许多来源的相关信息的仪表板。)

Immediately, I was faced with some challenges. 随即,我面临一些挑战。 Using WebAPI, we wanted to expose the web services as REST endpoints. 使用WebAPI,我们希望将Web服务公开为REST端点。 This works well for client applications and is very open. 这对于客户端应用程序非常有效,并且非常开放。 However, making server-to-server calls in .NET, I wanted to abstract away the REST calls and simply provide a method-based interface (so I could call, say, new MyWebServiceClient().getOrders() or something like that); 但是,在.NET中进行服务器到服务器的调用时,我想抽象出REST调用并仅提供基于方法的接口(因此我可以调用new MyWebServiceClient().getOrders()东西) ; I also did not want to have to duplicate data model classes across solutions, or worry about deserializing one JSON model type to another type. 我也不想在解决方案之间重复数据模型类,也不必担心将一种JSON模型类型反序列化为另一种类型。 (Blegh.) (死)

To achieve this goal, I've created an internal nuget package that a) provides access to the data model classes used in the service via the assembly, and b) provides an interface for HTTP calls, abstracting away the JSON serialization and deserialization, like so: 为了实现此目标,我创建了一个内部nuget包,其中a)通过程序集提供对服务中使用的数据模型类的访问,b)提供HTTP调用的接口,从而抽象出JSON序列化和反序列化,例如所以:

public async Task<T> Get<T>(string endpoint, IEnumerable<KeyValuePair<string, string>> parameters = null, CancellationToken cancellationToken = default(CancellationToken))
{
    var builder = new UriBuilder(Properties.Settings.Default.MyEndpointHost + endpoint);
    builder.Query = buildQueryStringFromParameters(parameters);

    _httpClient.DefaultRequestHeaders.Accept.Clear();
    _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    try
    {
        // After this, we really shouldn't continue.
        var request = await _httpClient.GetAsync(builder.Uri, cancellationToken);

        if (!request.IsSuccessStatusCode)
        {
            if (request.StatusCode >= HttpStatusCode.BadRequest && request.StatusCode < HttpStatusCode.InternalServerError)
            {
                throw new EndpointClientException("Service responded with an error message.", request.StatusCode, request.ReasonPhrase);
            }

            if (request.StatusCode >= HttpStatusCode.InternalServerError && (int)request.StatusCode < 600)
            {
                throw new EndpointServerException("An error occurred in the Service endpoint.", request.StatusCode, request.ReasonPhrase);
            }
        }

        var json = await request.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<T>(json);
    }
    catch (Exception ex)
    {
        throw;
    }
}

The public methods are simply convenience methods, calling that function with the requisite arguments, like this: 公共方法只是便捷方法,使用必要的参数调用该函数,如下所示:

    public async Task<IEnumerable<MyModel>> SearchMyModelsByFooName(string fooName, CancellationToken cancellationToken)
    {
        var parameters = new List<KeyValuePair<string, string>>();
        parameters.Add(new KeyValuePair<string, string>("searchText", fooName));

        return await this.Get<List<MyModel>>("myModel", parameters, cancellationToken);
    }

I've had good results with this, although I have to maintain it manually and update dependencies. 尽管我必须手动维护它并更新依赖项,但我取得了很好的效果。

However, upon talking to my colleagues, I was introduced to WCF, and it looks as though it solves a lot of the issues I'm trying to solve manually. 但是,在与同事交谈时,向我介绍了WCF,它似乎解决了我尝试手动解决的许多问题。 Looking into this, though, reveals that the setup can be tricky, and we're not sure if it's worth the trouble. 不过,调查一下发现该设置可能很棘手,我们不确定是否值得这样做。 (Additionally, we'd have to maintain two APIs.) (此外,我们必须维护两个API。)

Although it's fun, I don't want to reinvent the wheel. 虽然很有趣,但我不想重蹈覆辙。 Is there a way to bolt WCF on top of WebAPI for server-to-server calls only, or have WCF generate data for WebAPI controllers? 有没有一种方法可以将WCF固定在WebAPI之上,仅用于服务器到服务器的调用,或者WCF为WebAPI控制器生成数据?

If you don't need to use REST, and personally I don't see any reason to do this in a .NET server to server scenario, you could just create a WCF service to expose your data. 如果您不需要使用REST,而且就我个人而言,在.NET服务器到服务器方案中我看不到有任何理由这样做,则只需创建WCF服务即可公开您的数据。 Then generate proxy classes in your WebAPI that calls the WCF service. 然后在调用WCF服务的WebAPI中生成代理类。

Using svutil to generate the proxy classes make it easy to adapt to changes in WCF "API". 使用svutil生成代理类可以轻松适应WCF“ API”中的更改。 And you will have, as you call it, a method based interface to interact with the WCF service/s. 就像您所说的那样,您将具有一个基于方法的接口来与WCF服务进行交互。

Reference for using svutil: https://msdn.microsoft.com/en-us/library/ms733133(v=vs.110).aspx 使用svutil的参考: https ://msdn.microsoft.com/zh-cn/library/ms733133(v = vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM