一个数据接收接口项目中,要注意一些几点:
1、首先验证向我们发送数据的一方是否合法,其中就包括了:白名单、请求方式、请求的refer
2、数据接收之后,要验证接收参数的个数,参数类型是否合法,如果不合法,及时提示发送方发送不合法。
3、一般比较大的项目或者重要的项目,都会要求有运行日志,最好每一步都要有运行日志,便于及时发现出错的地方。
举例说明:(接口文件中无非就是一些if else 之类的语句,此处就不再说明,只写一些必要的函数)
1、验证白名单:
首先需要获取对方的IP地址: string ip = context.Request.UserHostAddress;
//是否是白名单
public bool IsIPWhite(string ip)
{
object IPWhite = System.Web.HttpContext.Current.Cache.Get("IPAshxWhite");//查看catch缓存中是否已经有ip ,节省查找时间
if (IPWhite == null)//如果没有,查找白名单的.txt文件
{
string path = AppDomain.CurrentDomain.BaseDirectory;// 获取程序的基目录。
string[] iparr = File.ReadAllLines(path + "/Doc/IP.txt");//打开已有文本文件,读取该文件的所有行,然后关闭
//System.Web.HttpContext.Current.Cache.Insert("IPAshxWhite", iparr, null, DateTime.Now.AddYears(1000), TimeSpan.Zero);
System.Web.HttpContext.Current.Cache.Insert("IPAshxWhite", iparr, new System.Web.Caching.CacheDependency(path + "/Doc/IP.txt"));//文件一旦修改,catch自动失效
}
object o = System.Web.HttpContext.Current.Cache.Get("IPAshxWhite");
string[] ipar = (string[])o;
bool IsRightip = false;
foreach (string ipp in ipar)
{
if (ip == ipp)
{
IsRightip = true;
break;
}
}
return IsRightip;
}
2 、验证请求是方式(以Post为例)
context.Request.HttpMethod.ToLower() == "post"
3、验证请求的refer
验证方法与白名单类似,只是需要提前获取对方请求的refer,为保证程序正常运行,我们需要首先对refer判空
<span style="font-size:18px;"> </span><span style="font-size:10px;"> Uri u = context.Request.UrlReferrer;
string strref = "";
if (u != null)
{
strref = context.Request.UrlReferrer.ToString();
}</span>
4、接收数据
<span style="font-size:18px;"> </span><span style="font-size:10px;"> string receivestr = "";
using (StreamReader sr = new StreamReader(context.Request.InputStream))
{
receivestr = sr.ReadToEnd();
}</span>
5、写日志
<span style="font-size:18px;"> </span><span style="font-size:10px;">/// <summary>
/// 将日志单独写出来
/// </summary>
/// <param name="strMemo"></param>
public static void WriteTBLog(string strMemo)
{
string filename = HttpContext.Current.Request.PhysicalApplicationPath;
//保存的路径
string time = DateTime.Now.ToString("yyyy-MM-dd");
filename = filename + "/Log/";
StreamWriter sr = null;
try
{
if (Directory.Exists(filename))//检查文件夹,没有到就自动创建
{
filename = filename + "" + "" + time + ".txt";
if (!File.Exists(filename))//检查今天的日志,如果没有,就自动创建,有,就追加内容
{
sr = File.CreateText(filename);
}
else
{
sr = File.AppendText(filename);
}
sr.WriteLine(strMemo);
}
else
{
Directory.CreateDirectory(filename);
filename = filename + "" + "" + time + ".txt";
if (!File.Exists(filename))
{
sr = File.CreateText(filename);
}
else
{
sr = File.AppendText(filename);
}
sr.WriteLine(strMemo);
}
}
catch
{ }
finally
{
if (sr != null)
sr.Close();
}
}</span>