简体   繁体   English

C#在生产中使用Json WebService

[英]C# Using a Json WebService in production

How should one write a library that is responsible for connecting to a restful api? 一个人应该如何编写一个负责连接静态api的库? The lib should provide methods for direct access for the api functions. lib应该提供直接访问api函数的方法。 Is using WebClient to get the response as string and Json.NET to deserialize them as objects a reliable, acceptable way of doing this? 使用WebClient以字符串形式获取响应,并使用Json.NET将其反序列化为对象是一种可靠的,可接受的方法吗?

ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;//the server uses a self signed SSL cert

using (WebClient client = new WebClient())
{
    client.Headers.Add("..", "....");
    string str = client.DownloadString("https://..../users/"+UserId+"/super-secret-data");     
}

you can make a class for each group of calls (user management, up/downloading data,...). 您可以为每组通话(用户管理,上传/下载数据等)创建一个类。 this class implements some functions (mapping the web calls). 此类实现一些功能(映射Web调用)。 so when you want to list all new member, then you can write 因此,当您要列出所有新成员时,您可以编写

var accounting = new Accounting();
var memberList = accounting.GetNewMember();

This function ( GetNewMember() ) is simply a wrapper. 这个函数(GetNewMember())只是一个包装器。 In the function you call the REST-full API get the JSON back an convert it into the result you want. 在该函数中,您调用REST-full API,将JSON返回,然后将其转换为所需的结果。

And for creating the URIs, you can use the string.Format(string, object[]) overloading. 对于创建URI,可以使用string.Format(string,object [])重载。

您可以这样做,也可以将代码生成与Visual Studio和swagger结合使用,以在解决方案中导入其余的Web api。

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

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