简体   繁体   English

如何通过创建像ASMX Web服务的实例来使用WebAPI

[英]how to use WebAPI by creating an instance of it like ASMX web service

I have Asp.NET WebApi as business layer. 我有Asp.NET WebApi作为业务层。 I want to call it's methods by simply calling business controllers. 我想通过简单地调用业务控制器来调用它的方法。 something like this: (but i'm not able to add this webapi like a service reference) 像这样的东西:(但我不能像服务参考那样添加这个webapi)

Business.API.UserController Users = new Business.API.UserController();
Users.GetAllUser();

previously i was working with WCF web services where i was able to create an instance of web service just by adding it through "Add Service References" and setting some Endpoints. 以前我正在使用WCF Web服务,我可以通过“添加服务引用”添加它并设置一些端点来创建Web服务实例。 I can't do that in WebAPI (I think). 我不能在WebAPI中做到这一点(我认为)。 i have read so many article about it but most of them was about calling it's method by HttpRequest. 我已经阅读了很多关于它的文章,但大多数都是关于通过HttpRequest调用它的方法。 in this way : 通过这种方式 :

using (var client = new HttpClient())    
{    
    client.BaseAddress = new Uri("http://localhost:38104/");
    client.DefaultRequestHeaders.Accept.Clear();    
    HttpResponseMessage response;    
    response = await client.GetAsync("api/Weather");    
    if (response.IsSuccessStatusCode)    
    {    
        WeatherClient[] reports = await response.Content.ReadAsAsync<WeatherClient[]>();                   
     }    
}    

I think it's a ridiculous using of an web service. 我认为使用Web服务是荒谬的。 am i wrong or there is something wrong with me ? 我错了还是我有问题?

While there is nothing wrong with you, that is also not a ridiculous way of using a web service. 虽然你没有任何问题,但这也不是一种使用网络服务的荒谬方式。 In fact; 事实上; its the only way to use a web service; 它是使用Web服务的唯一方式; WCF hid that code for you. WCF为您隐藏了该代码。

Disclaimer: There are other .NET classes and libraries that perform HTTP requests and may have a simpler API, but nothing that will hide it as a class like WCF 免责声明:还有其他.NET类和库执行HTTP请求,可能有一个更简单的API,但没有任何东西可以将它隐藏为像WCF这样的类

WCF services publish metadata about themselves, which is why "Service References" works. WCF服务发布关于他们自己的元数据,这就是“服务引用”的工作原理。 Web API does not have a similar concept, you have to manually do the HTTP request. Web API没有类似的概念,您必须手动执行HTTP请求。 You can of course wrap that code into some generic functions for reuse. 您当然可以将该代码包装到一些通用函数中以供重用。

With the right helper methods, you can get close to a "RPC" interface, just needing to pass in each method's endpoint instead of a name. 使用正确的帮助器方法,您可以接近“RPC”接口,只需要传入每个方法的端点而不是名称。

It's best for classes to depend on interfaces rather than directly instantiating an HttpClient . 类最好依赖于接口而不是直接实例化HttpClient I've seen applications that did this correctly with WCF services - depending on service interfaces - but then for Web APIs they throw away abstraction and directly incorporate Http requests. 我见过使用WCF服务正确执行此操作的应用程序 - 取决于服务接口 - 但是对于Web API,它们会丢弃抽象并直接合并Http请求。

Within your application you can still define an interface representing some service so that the implementation - Web API, mock, something else - is abstracted. 在您的应用程序中,您仍然可以定义代表某些服务的接口,以便抽象实现 - Web API,模拟,其他东西。

For example, you might depend on this interface 例如,您可能依赖于此接口

public interface IFooService
{
    FooDto GetFoo(Guid id);
    List<FooDto> GetAllFoos();
    Guid InsertFoo(FooInsertDto foo);
    void UpdateFoo(FooDto updating);
    void DeleteFoo(Guid id);
}

and use this implementation: 并使用此实现:

public class FooServiceClient : IFooService
{
    private readonly RestClient _restClient;

    public FooServiceClient(string baseUrl)
    {
        _restClient = new RestClient(baseUrl.TrimEnd('/'));
    }

    public FooDto GetFoo(Guid id)
    {
        var request = new RestRequest($"api/foo/get{id}", Method.GET);
        var foo = _restClient.Execute<FooDto>(request).Data;
        return foo;
    }

    public List<FooDto> GetAllFoos()
    {
        var request = new RestRequest("api/foo/getall", Method.GET);
        var foos = _restClient.Execute<List<FooDto>>(request).Data;
        return foos;
    }

    public Guid InsertFoo(FooInsertDto foo)
    {
        var request = new RestRequest("api/foo/insert", Method.POST)
            { RequestFormat = DataFormat.Json};
        request.AddBody(foo);
        return _restClient.Execute<Guid>(request).Data;
    }

    public void UpdateFoo(FooDto updating)
    {
        var request = new RestRequest("api/foo/update", Method.POST)
        { RequestFormat = DataFormat.Json };
        request.AddBody(updating);
        _restClient.Execute(request);
    }

    public void DeleteFoo(Guid id)
    {
        var request = new RestRequest("api/foo/delete", Method.POST)
        { RequestFormat = DataFormat.Json };
        request.AddBody(id);
        _restClient.Execute(request);
    }
}

This also demonstrates the use of RestSharp . 这也证明了RestSharp的使用。 It's not recommended to create and dispose an HttpClient for each use. 不建议为每次使用创建和配置HttpClient RestSharp helps manage that and provides methods to simplify sending requests and reading responses. RestSharp帮助管理它并提供简化发送请求和读取响应的方法。

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

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