Giter Site home page Giter Site logo

dotnetcore / webapiclient Goto Github PK

View Code? Open in Web Editor NEW
2.0K 110.0 439.0 7.3 MB

An open source project based on the HttpClient. You only need to define the c# interface and modify the related features to invoke the client library of the remote http interface asynchronously.

License: MIT License

C# 98.21% PowerShell 0.78% HTML 1.00%
webapi retrofit client restful httpclient webclient json xml form json-rpc-client

webapiclient's Introduction

介绍                    

集高性能高可扩展性于一体的声明式http客户端库。

文档

https://webapiclient.github.io/

webapiclient's People

Contributors

239573049 avatar ad313 avatar bao2314483 avatar barlowdu avatar cdpidan avatar dependabot[bot] avatar elderjames avatar ezrealj avatar fossabot avatar frisktale avatar gtxck avatar hjkl950217 avatar pengweiqhca avatar waleswood avatar xljiulang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webapiclient's Issues

参数加了MulitpartContent问题

[HttpPost("/api/UserBasicInfo/BindCredentials")] ITask<ResultModel<UserBasicInfoResult>> BindCredentials([MulitpartContent]Guid Id,[MulitpartContent]string CredentialsBackImg);

API接口接收CredentialsBackImg的值:
http%3a%2f%2fbaseservice%3a8104%2f%2fImgTemp%2f636616463453653498.jpg

有什么办法可以API接收能变回正常

配合Hangfire使用问题

我不知道作者你对Hangfire使用过没有,如果没有,你可以百度下,其实作用跟mq非常相似
那问题来了,因为WebApiClient使用接口来写访问api,导致Hangfire异步处理的时候没有办法找到对应接口的实例化类,不知道有什么解决办法
`[HttpHost("http://localhost:60708")]
public interface web1 : IHttpApi
{
[HttpGet("/api/Values")]
ITask Get();
}

public class webtest {
    public web1 web1 => HttpApiClient.Create<web1>();
}`

控制器
[HttpGet("Test")] public async Task<string> Test() { BackgroundJob.Enqueue<webtest>(x=> x.web1.Get()); return ""; }

错误提示:The type WebApiClientTest.web1 must be derived from the WebApiClientTest.webtest type.
Parameter name: type

这是Demo,不要在意细节,因为WebApiClient和Hangfire都是非常好用的插件来,我希望两者能无缝衔接

SetCookie() 存在Bug

return from item in cookieValues.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
       let kv = item.Split('=')
       let name = kv.FirstOrDefault().Trim()
       let value = kv.Length > 1 ? kv.LastOrDefault() : string.Empty
       let encode = HttpUtility.UrlEncode(value, encoding)
       select new Cookie(name, encode);

这里你用Split去处理,后面的Value也存在‘=’的话,你这里就会变成不止两段,而你却只获取最前和最后两段,是错误的。
另外这个地方我觉得不需要UrlEncode(这个你可以给我讲解一下为什么需要,谢谢)
我写了一段起码正确的代码如下:

       var list = new List<Cookie>();
       foreach (var item in Regex.Split(cookiesHeader, "; "))
       {
           var index = item.IndexOf('=');
           if (index < 0) continue;
           var name = item.Substring(0, index);
           var value = item.Substring(index + 1);
           list.Add(new Cookie(name, value));
       }

另外就是Cookie我觉得还有一个Bug,那就是序列化出来的CookieHeader居然用CookieContainer的SetCookie放进去只能得到一个值,简直让人无语。

aspnetcore2.1新增集成测试需求,能有HttpClient注入方式

以下是aspnetcore集成测试文档
https://docs.microsoft.com/zh-cn/aspnet/core/test/integration-tests?view=aspnetcore-2.2

里面WebApplicationFactory来运行要测试的aspnetcore项目,但是多各项目之间我是通过WebApiClient来互相调用的,但是集成测试只是暴露了HttpClient来访问接口,WebApiClient缺少配置HttpClient的方法,导致所有接口为了适应测试,都要自己实现一遍,工作量非常大,看能不能有一个注入方式注入HttpClient到WebApiClient里面去

全局拦截器添加建议

事例都是以下添加
c.GlobalFilters.Add(tokenFilter);
如果可以增加以下添加方式有助于拦截器的注入
c.GlobalFilters.Add();

当前源码报错

找不到接口XXXXAPIs.IAccount的代理类,请为接口所在项目重新使用Nuget安装WebApiClient.AOT 0.1.0.0

这个需要怎么解决?
请指教!

是否支持HTTPS API

是否支持HTTPS ?
我们请求https的API服务, 会报错
System.PlatformNotSupportedException: The handler does not support custom handling of certificates with this combination of libcurl (7.54.0) and its SSL backend ("LibreSSL/2.0.20").
at WebApiClient.ApiTask.ApiTaskOf`1.d__6.MoveNext()

HttpGet无法支持实体类中包含另一个实体类的情况

比如一个用户类,用户里面又有其他类,就直接将其他类中的字段变为用户类的字段了

实际想要的:http://localhost:50005/api/zh-CN/v1/CrudActions/test?Request.BrandName=444&Request.Status=1&PageIndex=1&PageSize=100
目前的:http://localhost:50005/api/zh-CN/v1/CrudActions/test?BrandName=444&Status=1&PageIndex=1&PageSize=100

可以看到Request这个类名被忽略了,导致服务端无法接收到数据

批量调用报错,程序集中有重复的类型名。

在 System.Reflection.Emit.ModuleBuilder.CheckTypeNameConflict(String strTypeName, Type enclosingType)
在 System.Reflection.Emit.AssemblyBuilderData.CheckTypeNameConflict(String strTypeName, TypeBuilder enclosingType)
在 System.Reflection.Emit.TypeBuilder.Init(String fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module, PackingSize iPackingSize, Int32 iTypeSize, TypeBuilder enclosingType)
在 System.Reflection.Emit.ModuleBuilder.DefineType(String name, TypeAttributes attr, Type parent)
在 WebApiClient.HttpApiClientProxy.ImplementAsHttpApiClient(Type interfaceType, MethodInfo[] apiMethods)
在 System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
在 WebApiClient.HttpApiClientProxy.CreateProxyWithInterface(Type interfaceType, IApiInterceptor interceptor)
在 WebApiClient.HttpApiClient.Create[TInterface](HttpApiConfig httpApiConfig)
在 Doc.LabelTypeMapper.Add(LabelType t) 位置 C:\Users\Administrator\Documents\Visual Studio 2015\Projects\百美__SCHEMA\PackingSlip\K【软件】项目源代码\2.0\Document\LabelTypeMapper.cs:行号 48
在 SDK.FedEx.ExpressDomesticShipClient.ExpressDomesticShipService_ReplySuccess(ProcessShipmentReply reply) 位置 C:\Users\Administrator\Documents\Visual Studio 2015\Projects\百美__SCHEMA\PackingSlip\K【软件】项目源代码\2.0\SDK\FedEx\ExpressDomesticShipClient.cs:行号 44
在 SDK.FedEx.BaseShipClient.Reply() 位置 C:\Users\Administrator\Documents\Visual Studio 2015\Projects\百美__SCHEMA\PackingSlip\K【软件】项目源代码\2.0\SDK\FedEx\BaseShipClient.cs:行号 134

autofac如何进行批量注入

文档里提供的autofac的注入方式是这样的
builder.Register(_ => new HttpApiFactory()
.ConfigureHttpApiConfig(c =>
{
c.HttpHost = new Uri("http://localhost:9999/");
c.FormatOptions.DateTimeFormat = DateTimeFormats.ISO8601_WithMillisecond;
}))
.As<IHttpApiFactory>()
.SingleInstance();

builder.Register(c => c.Resolve<IHttpApiFactory>().CreateHttpApi())
.As()
.InstancePerHttpRequest();

希望根据包扫描自动的注入所有的接口,我的有两个想法
一、提供HttpApiFactory的重载给使用者自已实现扫包,自已注入,需要这样的重载方法
HttpApiFactory(Type type)
使用时是这样的
new HttpApiFactory(typeof(IMyWebApi))
或new HttpApiFactory(type)

二、提供autofac扫包的扩展方法
通过包扫描出所有继承于IHttpApi接口,然后批量注入到容器里。
autofac的扩展后,能过调用方法就能自动注入,类似于以下用法
builder.RegisterAssemblyTypes(Assembly.GetCallingAssembly()).AsImplementedIHttpApi()
重点在于AsImplementedIHttpApi(),自动扫包自动注入

使用MulitpartFile上传文件的问题

Hi @xljiulang,这个项目很合我的胃口,尤其是基于特性的声明式语法和可扩展性极强的过滤器。我想知道WebApiClient如何使用MulitpartFile来上传文件,因为基于HttpWebRequest/HttpWebResponse这套API需要拼接大量的字符串,以构造类似下面的结构:

Content-type: multipart/form-data, boundary=AaB03x
--AaB03x
content-disposition: form-data; name="field1"
Joe Blow
--AaB03x
content-disposition: form-data; name="pics"; filename="file1.txt"
Content-Type: text/plain
--AaB03x--

虽然后续有了HttpClient这套API,可以通过MultipartFormDataContent来简化这套操作,但有时候还是会感觉不顺手,比如将文件流和键值对一起上传这种场景,那么,我的问题是,WebApiClient中支持上传这一功能的相关特性有哪些呢?我注意到两点,WebApiClient中提供了MulitpartFile这个类,WebApiClient支持HttpContent及其子类,那么该如何使用MulitpartFile完成上传这个功能呢?

支持通过 Swagger 文档生成调用客户端,以及服务发现

Hi
WebApiClient 是一个很好的开源项目 我很喜欢其设计思维,用起来很方便,我想 如果我们能够通过Swagger生成客户端 这将会更棒了,这样很好的和其他语言提供的API很好的进行融合调用

另外 可以考虑增加服务发现配置的 Atrribute,以及在创建代理访问实现的时候 增加一些常用的客户端负责算法,通过服务发现的配置来找到对应的服务,
像 Spring Cloud Feign 这类

.Net 4.7 下调用,报错

通过nuget下载的 Laojiu.WebAppClient 1.2.2
.Net 4.5 使用时正常,升级到.Net 4.7 后调用报错
System.Exception:“找不到方法:“System.Net.Http.HttpResponseMessage WebApiClient.Contexts.ApiActionContext.get_ResponseMessage()”。”
看源码预编译是.Net 4.5 的,是否有其他童鞋在4.7下使用过?

请求数组有误问题

访问接口定义
[HttpPost("api/Province/GetList")] ITask<ResultList<Province>> GetList([MulitpartContent]ProvinceListReq ReqData);

public class ProvinceListReq { public string[] ProvinceId { get; set; } public string PId { get; set; } public string PName { get; set; } public ProvinceType? Ptype { get; set; } }

请求(这是我代码,不要在意)
var plist = await this.Remote.Comm.Province.GetList(new ProvinceListReq() { Ptype= ProvinceType.Province });

然后API那边接收参数发现
ProvinceId的值会变成数组里面多了一个null
意思就是ProvinceId[0]的值是null,这样明显是错的,因为我没有传,ProvinceId应该是null

请教一个问题

我有一个很耗时的API调用,请问,无返回的调用该怎么写,无返回,受超时设置限制吗?

TokenResult

IdTken-IdToken 是写错了,还是表达什么意思?

全局拦截器改变访问接口返回值的问题

我实现IApiActionAttribute接口,想通过拦截访问接口时候出现500,401状态的时候,改变接口返回值
public Task OnEndRequestAsync(ApiActionContext context) { if(context.ResponseMessage.StatusCode==HttpStatusCode.InternalServerError) context.Result="报错啦" return Task.CompletedTask; }

但是我发现context.Result是只读属性,然而我看到IApiReturnAttribute接口,我实现了,但是
config.GlobalFilters.Add方法却只能添加实现IApiActionAttribute接口的类,请问IApiReturnAttribute具体怎么使用

重大急问题:我引用了WebApiClient.JIT 发现一把现目放到ABP框架中就抛异常。任何代码还没有写呢。

我换成AOT也不行。这是什么原因呀?

An unhandled exception occurred while processing the request.
FileNotFoundException: Could not load file or assembly 'RS.WeChatSdk, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null'. 系统找不到指定的文件。
Unknown location

ReflectionTypeLoadException: Unable to load one or more of the requested types.
Could not load file or assembly 'RS.WeChatSdk, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null'. 系统找不到指定的文件。
System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)

Loader Exceptions:
Could not load file or assembly 'RS.WeChatSdk, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null'. 系统找不到指定的文件。

Post方式传送base64报错

[HttpPost("/api/AliMarket/OcrIdCard")] ITask<ResultModel<OcrIdCardResult>> OcrIdCard(string FaceBase64Image, string BackBase64Image);

错误提示:
UriFormatException: Invalid URI: The Uri string is too long.
System.Uri.CreateThis(string uri, bool dontEscape, UriKind uriKind)
System.Uri..ctor(string uriString)
WebApiClient.Attributes.PathQueryAttribute.UsePathQuery(Uri uri, IEnumerable<KeyValuePair<string, string>> keyValues)
WebApiClient.Attributes.PathQueryAttribute+d__14.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
WebApiClient.Contexts.ApiActionContext+d__27.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
WebApiClient.ApiTask+ApiTaskOf+d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
CHY.BusinessService.UserService.Service.UserBaseSerivce+d__12.MoveNext() in UserBaseSerivce.cs

请求输出到控制台失败

image

image

image

“ConsoleLoggerExtensions.AddConsole(ILoggerFactory)”已过时:“This method is obsolete and will be removed in a future version. The recommended alternative is AddConsole(this ILoggingBuilder builder).”

控制台并没有输出请求

error : WebApiClient -> 找不到类型:WebApiClient.HttpApiClient

使用 WebApiClient.AOT,

[HttpHost("http://192.168.56.254:85")]
    public interface ICqService : IHttpApi
    {
        [HttpPost("/cq/last")]
        ITask<UpdateCqResult> LastNum();
    }
 var client = HttpApiClient.Create<ICqService>();

编译时报错

1>------ 已启动生成: 项目: WBot, 配置: Debug Any CPU ------
1>  WebApiClient -> WebApiClient.BuildTask.ProxyTask, WebApiClient.BuildTask, Version=0.1.6.0, Culture=neutral, PublicKeyToken=dc657b230a4e635f
1>  WebApiClient -> 添加搜索目录: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5
1>  WebApiClient -> Failed to resolve assembly: 'Prism.Wpf, Version=7.1.0.431, Culture=neutral, PublicKeyToken=40ee6c3a2184dc59'
1>  WebApiClient -> Failed to resolve assembly: 'Miae.Prism, Version=1.0.0.18, Culture=neutral, PublicKeyToken=null'
1>  WebApiClient -> Failed to resolve assembly: 'Prism, Version=7.1.0.431, Culture=neutral, PublicKeyToken=40ee6c3a2184dc59'
1>  WebApiClient -> Failed to resolve assembly: 'Miae.Core, Version=1.0.0.10, Culture=neutral, PublicKeyToken=null'
1>  WebApiClient -> Failed to resolve assembly: 'WebApiClient.AOT, Version=0.3.0.0, Culture=neutral, PublicKeyToken=96ac13f3a45093d9'
1>  WebApiClient -> Failed to resolve assembly: 'NimCore, Version=5.0.0.0, Culture=neutral, PublicKeyToken=null'
1>  WebApiClient -> Failed to resolve assembly: 'Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
1>  WebApiClient -> Failed to resolve assembly: 'CommonServiceLocator, Version=2.0.4.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0'
1>  WebApiClient -> Failed to resolve assembly: 'NimUtility, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null'
1>  WebApiClient -> Failed to resolve assembly: 'ServiceLocation, Version=1.3.1.0, Culture=neutral, PublicKeyToken=null'
1>E:\LW\Projects\Miae\MiaePlugins\WBot\packages\WebApiClient.AOT.0.3.0\build\net45\WebApiClient.AOT.targets(12,5): error : WebApiClient -> 找不到类型:WebApiClient.HttpApiClient
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========

How can I get http response status code when I use Handle() method?

As following code shown:

var proxy = HttpApiClient.Create<IMyInterace>();
var result = await proxy.CallRemoteApiAsync( ... )
    .Handle().WhenCatch<Exception>(e => {
        // do something

        return new SomeResult { 
            StatusCode = ????.StatusCode,
            Message = "Some message",
            Success = false
        };
    });

When I create SomeResult, I need a given status code from HttpClient encapsulated within HttpApiClient. How can I get such status code?

跟MvvmCross不兼容

在wpf+mvvmcross 中只要有类继承IHttpApi, 就会导致运行时无法显示界面, 也不报错..... 这问题找了我老半天... 把IhttpApi继承去掉界面就显示了, 求解, 就用MvvmCross官方的Demo试一下

Timeout问题

调用方设置超时时间为3分钟,被调用方执行时间小于3分钟,调用方会报超时错误,大概100秒左右超时,难道是HttpClient本身不能支持超过100秒的超时时间?

时间格式序列化

services.AddHttpApiTypedClient<IOvoparkApi>(c => { c.LoggerFactory = new LoggerFactory().AddConsole(); c.FormatOptions.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; });
image
一人血书求支持DateTimeOffset日期格式设置

当地址不存在时,返回的错误有问题,提示未将对象引用到对象实例

发生了 System.NullReferenceException
HResult=0x80004003
Message=未将对象引用设置到对象的实例。
Source=WebApiClient
StackTrace:
at WebApiClient.Attributes.ApiReturnAttribute.WebApiClient.Interfaces.IApiReturnAttribute.GetTaskResult(ApiActionContext context) in D:\项目\WebApiClient-master\WebApiClient\Attributes\ReturnAttributes\ApiReturnAttribute.cs:line 32
at WebApiClient.ApiTask.ApiTaskOf1.<RequestAsync>d__7.MoveNext() in D:\项目\WebApiClient-master\WebApiClient\Internal\ApiTask.cs:line 179 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at WebApiClient.ApiTask.ApiTaskOf1.<RequestAsync>d__6.MoveNext() in D:\项目\WebApiClient-master\WebApiClient\Internal\ApiTask.cs:line 129 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Demo.Program.d__4.MoveNext() in D:\项目\WebApiClient-master\Demo\Program.cs:line 71
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Demo.Program.d__1.MoveNext() in D:\项目\WebApiClient-master\Demo\Program.cs:line 41

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.