在维护旧的项目时,有时需要提供APP连接的需求,就要提供HTTP服务,winform项目就要提供HTTP服务,就不用再去写个c# web的IIS相关的业务了,简化项目的复杂度。只需要简单化实例就可以实现提供HTTP服务
源码CDSN下载
原先的业务get,post,请求返回文件功能全有
最新添加了权限认证的功能,业务接口只有获取正确的token后才能通信
1)验证通过后才能获取token
2)token可以设置定时过期
3)token里面可以绑定用户信息
//这里是部分代码,动态添加token,判断token是否存在,定时处理过期的token
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace webAPINancy.Common
{
public class UnidDo
{
public static Dictionary<string, JObject> unidMap = new Dictionary<string, JObject>();
private static readonly object unid_Lock = new object();
public static string Add(string information) {
string result = ""; ;
try {
lock (unid_Lock)
{
string key = Guid.NewGuid().ToString();
if (!unidMap.ContainsKey(key))
{
string strDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
JObject json = new JObject();
json.Add(new JProperty("DateTime", strDate));
json.Add(new JProperty("information", information));
unidMap.Add(key, json);
result = key;
}
else {
result = Add(information);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Add()--->" + ex.Message);
return result;
}
return result;
}
public static void AutoDelKey()
{
try {
while (true) {
System.Threading.Thread.Sleep(1000*20);//每20秒遍历一次
lock (unid_Lock)
{
List<string> list = new List<string>();
foreach (KeyValuePair<string, JObject> kvp in unidMap)
{
JObject json = kvp.Value;
DateTime oldDateTime = DateTime.Parse(json["DateTime"].ToString());
if ((DateTime.Now- oldDateTime).TotalSeconds > 60*1) //当key的保存时间大于60秒就删除失效
{
list.Add(kvp.Key);
}
}
for (int i = 0; i < list.Count; i++)
{
unidMap.Remove(list[i]);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("AutoDelKey()--->" + ex.Message);
}
}
public static bool unidContainsKey(string key) {
bool result = false;
try
{
lock (unid_Lock)
{
if (unidMap.ContainsKey(key))
{
JObject json = unidMap[key];
json["DateTime"]= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
unidMap[key] = json;
result = true;
}
}
}
catch (Exception ex)
{
Console.WriteLine("unidContainsKey()--->" + ex.Message);
return result;
}
return result;
}
}
}