HttpServer 类 |
命名空间: HslCommunication.Enthernet
HttpServer 类型公开以下成员。
名称 | 说明 | |
---|---|---|
HttpServer |
实例化一个默认的对象,当前的运行,需要使用管理员的模式运行 Instantiate a default object, the current operation, you need to use the administrator mode to run |
名称 | 说明 | |
---|---|---|
ApiCalledAction |
获取或设置当前接口调用信息处理的委托,可以用于对接口调用的二次分析,在接口调用完成的时候,将触发本委托 Obtain or set the delegate for the current interface call information processing, which can be used for secondary analysis of the interface call, and the delegate will be triggered when the interface call is completed | |
DealWithHttpListenerRequest |
额外的处理请求信息的委托定义,将可以自定义处理一些特殊的请求头数据,例如一些账户相关的其他属性,语言属性等等。 Additional delegate definitions for processing request information will be able to customize some special request header data, such as some other account-related attributes, language attributes, and so on. | |
HandleFileUpload |
获取或设置当前的自定义处理文件上传的信息,自动解析好文件的基本信息 Obtain or set the current custom processing file upload information, and automatically parse the basic information of the file | |
HandleRequestFunc |
获取或设置当前的自定义的处理信息,如果不想继承实现方法,可以使用本属性来关联你自定义的方法。 Get or set the current custom processing information. If you don't want to inherit the implementation method, you can use this attribute to associate your custom method. | |
IsCrossDomain |
获取或设置是否支持跨域操作 Get or set whether to support cross-domain operations | |
LogNet | ||
LogStatistics |
获取当前的日志统计信息,可以获取到每个API的每天的调度次数信息,缓存60天数据,如果需要存储本地,需要调用SaveToFile(String)方法。 Get the current log statistics, you can get the daily scheduling times information of each API, and cache 60-day data. If you need to store it locally, you need to call the SaveToFile(String) method. | |
Port |
获取当前的端口号信息 Get current port number information | |
ServerEncoding |
获取或设置当前服务器的编码信息,默认为UTF8编码 Get or set the encoding information of the current server, the default is UTF8 encoding |
名称 | 说明 | |
---|---|---|
Close |
关闭服务器 Shut down the server | |
Equals | Determines whether the specified object is equal to the current object. (继承自 Object。) | |
Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (继承自 Object。) | |
GetAllRpcApiInfo |
获取当前所有注册的RPC接口信息,将返回一个数据列表。 Get all currently registered RPC interface information, and a data list will be returned. | |
GetHashCode | Serves as the default hash function. (继承自 Object。) | |
GetMethodName |
根据完整的地址获取当前的url地址信息
| |
GetType | Gets the Type of the current instance. (继承自 Object。) | |
HandleObjectMethod(HttpListenerRequest, String, String, MqttRpcApiInfo, ActionHttpListenerRequest, ISessionContext) |
使用指定的对象来返回网络的API接口,前提是传入的数据为json参数,返回的数据为json数据,详细参照说明 Use the specified object to return the API interface of the network, provided that the incoming data is json parameters and the returned data is json data, please refer to the description for details | |
HandleObjectMethod(HttpListenerRequest, String, String, Object, ActionHttpListenerRequest, ISessionContext) |
使用指定的对象来返回网络的API接口,前提是传入的数据为json参数,返回的数据为json数据,详细参照说明 Use the specified object to return the API interface of the network, provided that the incoming data is json parameters and the returned data is json data, please refer to the description for details | |
HandleRequest |
根据客户端的请求进行处理的核心方法,可以返回自定义的数据内容,只需要集成重写即可。 The core method of processing according to the client's request can return custom data content, and only needs to be integrated and rewritten. | |
MemberwiseClone | Creates a shallow copy of the current Object. (继承自 Object。) | |
RegisterHttpRpcApi(Object) |
注册一个RPC的服务接口,可以指定当前的控制器名称,以及提供RPC服务的原始对象 Register an RPC service interface, you can specify the current controller name, and the original object that provides the RPC service | |
RegisterHttpRpcApi(String, Object) |
注册一个RPC的服务接口,可以指定当前的控制器名称,以及提供RPC服务的原始对象 Register an RPC service interface, you can specify the current controller name, and the original object that provides the RPC service | |
SetLoginAccessControl |
设置登录的账户信息,如果需要自己控制,可以自己实现委托HandleRequestFunc Set the login account information, if you need to control by yourself, you can implement the delegation by yourselfHandleRequestFunc | |
Start |
启动服务器,正常调用该方法时,应该使用try...catch...来捕获错误信息 Start the server and use try...catch... to capture the error message when calling this method normally | |
ToString | Returns a string that represents the current object. (重写 ObjectToString.) | |
UnRegisterHttpRpcApi(Object) |
卸载一个已经注册的RPC接口,想要卸载指定的接口,此处就需要传入注册时一样的参数 Uninstall a registered RPC interface. If you want to uninstall the specified interface, you need to pass in the same parameters as the registration | |
UnRegisterHttpRpcApi(String, Object) |
卸载一个已经注册的RPC接口,想要卸载指定的接口,此处就需要传入注册时一样的参数 Uninstall a registered RPC interface. If you want to uninstall the specified interface, you need to pass in the same parameters as the registration | |
UseHttps |
使用HTTPS模式,关于如何使用证书,具体的教程可以参考:http://www.hsltechnology.cn/Doc/HslCommunication?chapter=HslCommChapter6-5 For more information about how to use the certificate in the HTTPS mode, please refer to http://www.hsltechnology.cn/Doc/HslCommunication?chapter=HslCommChapter6-5 |
名称 | 说明 | |
---|---|---|
ToJsonString |
获取当前对象的JSON格式表示的字符串。 (由 HslExtension 定义。)Gets the string represented by the JSON format of the current object. |
private HttpServer httpServer; // 当前的Web服务器,支持web api来通信的方式 private void Start( ) { // 启动web的服务器 try { this.httpServer = new HttpServer( ); this.httpServer.Start( 8000 ); } catch (Exception ex) { Console.WriteLine( "Web服务器加载失败!" + ex.Message ); } } // 调用start方法之后,我们打开浏览器,输入 http://127.0.0.1:8000 就可以看到如下的文本 "This is HslWebServer, Thank you for use!" // After calling the start method, we open the browser and enter http://127.0.0.1:8000 to see the following text: "This is HslWebServer, Thank you for use!"
private HttpServer httpServer; // 当前的Web服务器,支持web api来通信的方式 private void Start( ) { // 启动web的服务器 try { this.httpServer = new HttpServer( ); this.httpServer.HandleRequestFunc = HandleRequest; this.httpServer.Start( 8000 ); } catch (Exception ex) { Console.WriteLine( "Web服务器加载失败!" + ex.Message ); } } private string HandleRequest( HttpListenerRequest request, HttpListenerResponse response, string data ) { if (request.HttpMethod == "GET") { return "This is Get Method"; } else if (request.HttpMethod == "POST") { return "This is Post Method"; } else { return string.Empty; } }
private string HandleRequest( HttpListenerRequest request, HttpListenerResponse response, string data ) { if (request.HttpMethod == "GET") { if (request.RawUrl == "/GetA") { return "This is GetA Method"; } else if (request.RawUrl == "/GetB") { return "This is GetB Method"; } else { return "This is Notsupported Method"; } } else if (request.HttpMethod == "POST") { if (request.RawUrl == "/PostA") { Console.WriteLine( data ); // data 就是post上来的数据信息 return "OK"; } return "This is Post Method"; } else { return string.Empty; } }
private string HandleRequest( HttpListenerRequest request, HttpListenerResponse response, string data ) { // 下面的对授权验证增加用户名和密码的操作,当使用浏览器登录的时候,会自动弹出输入用户名及密码的窗口 // The following operation for adding a username and password for authorization verification will automatically pop up a window for // entering the username and password when logging in with a browser. string[] values = request.Headers.GetValues( "Authorization" ); if (values == null || values.Length < 1 || string.IsNullOrEmpty( values[0] )) { response.StatusCode = 401; response.AddHeader( "WWW-Authenticate", "Basic realm=\"Secure Area\"" ); return ""; } string base64String = values[0].Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries )[1]; string accountString = Encoding.UTF8.GetString( Convert.FromBase64String( base64String ) ); string[] account = accountString.Split( new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries ); if (account.Length < 2) { response.StatusCode = 401; response.AddHeader( "WWW-Authenticate", "Basic realm=\"Secure Area\"" ); return ""; } // 此处假定用户名和密码限定了 admin 123456 if (!(account[0] == "admin" && account[1] == "123456")) { response.StatusCode = 401; response.AddHeader( "WWW-Authenticate", "Basic realm=\"Secure Area\"" ); return ""; } if (request.HttpMethod == "GET") { if (request.RawUrl == "/GetA") { return "This is GetA Method"; } else if (request.RawUrl == "/GetB") { return "This is GetB Method"; } else { return "This is Notsupported Method"; } } else if (request.HttpMethod == "POST") { if (request.RawUrl == "/PostA") { Console.WriteLine( data ); // data 就是post上来的数据信息 return "OK"; } return "This is Post Method"; } else { return string.Empty; } }
private string HandleRequest( HttpListenerRequest request, HttpListenerResponse response, string data ) { if (request.HttpMethod == "GET") { if (request.RawUrl == "/GetA") // 当浏览器浏览一个网页的时候,输入 http://127.0.0.1:6000/GetA 会显示网络内容 { response.AddHeader( "Content-type", $"Content-Type: text/html; charset=utf-8" ); return "<html><head><title>HslWebServer</title></head><body><p style=\"color: red\">这是一个测试的消息内容</p></body></html>"; } else { return "This is Notsupported Method"; } } else if (request.HttpMethod == "POST") { return "This is Post Method"; } else { return string.Empty; } }
private HttpServer httpServer; // 当前的Web服务器,支持web api来通信的方式 private void Start( ) { // 启动web的服务器 try { this.httpServer = new HttpServer( ); this.httpServer.RegisterHttpRpcApi( this ); // 将当前类的方法接口(带HslMqttApi特性)注册为RPC接口 // 如果需要控制账户登录的情况,如果不需要,直接注释下面的三行代码 this.httpServer.SetLoginAccessControl( new HslCommunication.MQTT.MqttCredential[] { new HslCommunication.MQTT.MqttCredential("admin", "123456")} ); // 启动服务 this.httpServer.Start( 8000 ); } catch (Exception ex) { Console.WriteLine( "Web服务器加载失败!" + ex.Message ); } } [HslCommunication.Reflection.HslMqttApi(Description = "这是求加法结果的RPC接口", HttpMethod = "GET")] public int Add( int a, int b ) { return a + b; } /// <summary> /// 一个更高级的RPC接口,用来校验用户名,密码,并且返回是否校验成功的结果 /// </summary> /// <param name="name">用户名</param> /// <param name="password">密码</param> /// <returns>是否校验成功的结果</returns> [HslCommunication.Reflection.HslMqttApi( Description = "校验用户名,密码,并且返回是否校验成功的结果,name:用户名 password:密码", HttpMethod = "GET" )] public HslCommunication.OperateResult<string> CheckAccount( string name, string password ) { if (name == null) return new HslCommunication.OperateResult<string>( "user name can not be null" ); if (password == null) return new HslCommunication.OperateResult<string>( "pwd can not be null" ); if (name == "admin" && password == "123456") return HslCommunication.OperateResult.CreateSuccessResult( "" ); return new HslCommunication.OperateResult<string>( "account or pwd wrong" ); } public class UserData { public string Name { get; set; } = "Name"; public string A { get; set; } = "A"; public string B { get; set; } = "B"; } /// <summary> /// 甚至参数可以定义为自定义类型,不过需要确保可以从json转换,自定义类型的接口使用 POST 方式,更好的传参 /// 本接口示例就是回传用户的名字 /// </summary> /// <param name="userData">用户对象</param> /// <returns>返回用户的名称</returns> [HslCommunication.Reflection.HslMqttApi( Description = "回传用户的名字,参数为 UserData 对象", HttpMethod = "POST" )] public HslCommunication.OperateResult<string> GetName( UserData userData ) { return HslCommunication.OperateResult.CreateSuccessResult( userData.Name ); } // 下面演示带安全策略的接口,我有一个接口是需要面向指定用户的,而不是所有用户都可以调用的 // 那么需要参考启动的时候进行账户检查,这里演示,只能 admin 账户可以调用下面的方法 /// <summary> /// 这是一个计算数据的RPC接口 /// </summary> /// <param name="sessionContext">会话内容</param> /// <param name="a">参数a</param> /// <param name="b">参数b</param> /// <returns>返回计算结果</returns> [HslCommunication.Reflection.HslMqttApi( Description = "这是一个计算数据的RPC接口,只能admin账户调用,a:参数a b:参数b", HttpMethod = "GET" )] public HslCommunication.OperateResult<int> Calculate( HslCommunication.Core.ISessionContext sessionContext, int a, int b ) { if (sessionContext.UserName == "admin") return HslCommunication.OperateResult.CreateSuccessResult( a * b ); return new HslCommunication.OperateResult<int>( "Not supported" ); }