我有Asp.NET WebApi作为业务层。我想通过简单地调用业务控制器来调用它的方法。像这样的东西:(但我不能像服务参考那样添加这个webapi)
Business.API.UserController Users = new Business.API.UserController();
Users.GetAllUser();
以前我正在使用WCF Web服务,我可以通过“添加服务引用”添加它并设置一些端点来创建Web服务实例。我不能在WebAPI中做到这一点(我认为)。我已经阅读了很多关于它的文章,但大多数都是关于通过HttpRequest调用它的方法。通过这种方式 :
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[]>();
}
}
我认为使用Web服务是荒谬的。我错了还是我有问题?
虽然你没有任何问题,但这也不是一种使用网络服务的荒谬方式。事实上;它是使用Web服务的唯一方式; WCF为您隐藏了该代码。
免责声明:还有其他.NET类和库执行HTTP请求,可能有一个更简单的API,但没有任何东西可以将它隐藏为像WCF这样的类
WCF服务发布关于他们自己的元数据,这就是“服务引用”的工作原理。 Web API没有类似的概念,您必须手动执行HTTP请求。您当然可以将该代码包装到一些通用函数中以供重用。
使用正确的帮助器方法,您可以接近“RPC”接口,只需要传入每个方法的端点而不是名称。
类最好依赖于接口而不是直接实例化HttpClient
。我见过使用WCF服务正确执行此操作的应用程序 - 取决于服务接口 - 但是对于Web API,它们会丢弃抽象并直接合并Http请求。
在您的应用程序中,您仍然可以定义代表某些服务的接口,以便抽象实现 - Web API,模拟,其他东西。
例如,您可能依赖于此接口
public interface IFooService
{
FooDto GetFoo(Guid id);
List<FooDto> GetAllFoos();
Guid InsertFoo(FooInsertDto foo);
void UpdateFoo(FooDto updating);
void DeleteFoo(Guid id);
}
并使用此实现:
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);
}
}
这也证明了使用RestSharp。不建议为每次使用创建和处理HttpClient
。 RestSharp帮助管理它并提供简化发送请求和读取响应的方法。