在Winform,Silvelight,WPF等程序中访问Asp.net MVC web api
2012-11-08 19:53 JustRun 阅读(1648) 评论(0) 编辑 收藏 举报Asp.net mvc 4中出现的web api是用来实现REST.
关于什么是REST,可以看这里http://zh.wikipedia.org/zh/REST
通过ajax等访问 web api非常方便,但是如何在Winform, Silverlight等访问web api呢?
通过搜索,发现了已经有人做过这个东西了,就是RestSharp.
https://github.com/restsharp/RestSharp
RestSharp不只是访问web api, 访问其他平台的Rest API也是一样。
看看介绍的使用,无论是post数据,文件,格式化返回数据,异步请求都非常方便:
var client = new RestClient("http://example.com"); // client.Authenticator = new HttpBasicAuthenticator(username, password); var request = new RestRequest("resource/{id}", Method.POST); request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method request.AddUrlSegment("id", 123); // replaces matching token in request.Resource // add parameters for all properties on an object request.AddObject(object); // or just whitelisted properties request.AddObject(object, "PersonId", "Name", ...); // easily add HTTP Headers request.AddHeader("header", "value"); // add files to upload (works with compatible verbs) request.AddFile(path); // execute the request RestResponse response = client.Execute(request); var content = response.Content; // raw content as string // or automatically deserialize result // return content type is sniffed but can be explicitly set via RestClient.AddHandler(); RestResponse<Person> response2 = client.Execute<Person>(request); var name = response2.Data.Name; // or download and save file to disk client.DownloadData(request).SaveAs(path); // easy async support client.ExecuteAsync(request, response => { Console.WriteLine(response.Content); }); // async with deserialization var asyncHandle = client.ExecuteAsync<Person>(request, response => { Console.WriteLine(response.Data.Name); }); // abort the request on demand asyncHandle.Abort();

本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名justrun(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述