一种类似Retrofit声明接口即可实现调用的WebApi客户端框架

时间:2023-03-09 20:01:56
一种类似Retrofit声明接口即可实现调用的WebApi客户端框架

为.Net出力

java有okhttp,还在okhttp这上搞了一个retrofit,.net有HttpClient,但目前我没有发现有类似的retrofit框架。最近在搞mqtt的webApi封装,输出很多web api接口,给移动端也有给后台二次开发使用的,所以有了搞一个类似retrofit的.net实现,项目叫WebApiClient,托管在 https://github.com/xljiulang/WebApiClient

WebApiClient使用

一个原则:声明它,然后调用它,不要实现它。

namespace Demo
{
    [JsonReturn]
    [HttpHost("http://www.mywebapi.com")]
    public interface MyWebApi
    {
        [HttpGet("/webapi/{type}/about")] // GET webapi/typeValue/about
        Task<ApiResult<string>> GetAboutAsync(string type);

        [HttpGet("/webapi/user")]  // GET webapi/user?userName=aa&nickName=bb&&BeginTime=cc&EndTime=dd
        Task<ApiResult<UserInfo>> GetUserAsync(string userName, string nickName, TimeFilter timeFilter);

        [HttpPut("/webapi/user")] // PUT webapi/user
        Task<ApiResult<bool>> UpdateUserAsync([JsonContent] UserInfo loginInfo);

        [HttpDelete("/webapi/user")] // DELETE  webapi/user?id=idValue
        Task<ApiResult<bool>> DeleteUserAsync(string id);

        [HttpDelete("/webapi/user/{id}")] // DELETE  webapi/user/idValue
        Task<ApiResult<bool>> DeleteUser2Async(string id);
    }
}
namespace Demo
{
    class Program
    {
        static async void Test()
        {
            var myWebApi = new WebApiClient.HttpApiClient().GetHttpApi<MyWebApi>();

            await myWebApi.GetAboutAsync("typeValue");
            " });
            await myWebApi.DeleteUser2Async(id: "id001");
        }

        static void Main(string[] args)
        {
            Test();
            Console.ReadLine();
        }
    }
}

调用它吧

项目维护

这是一个很嫩的项目,开发还不到三天,未来我会持续维护,类似NetworkSocket项目。