一、基本配置


  1. 全局配置 Global.asax

  1. public class WebApiApplication : System.Web.HttpApplication
  2. {
  3.   protected void Application_Start()
  4.   {
  5.     GlobalConfiguration.Configure(WebApiConfig.Register);
  6.     GlobalConfiguration.Configuration.Filters.Add(new WebApiActionDebugFilter());
  7.  
  8.     //配置返回的时间类型数据格式
  9.     GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
  10.       new Newtonsoft.Json.Converters.IsoDateTimeConverter()
  11.     {
  12.       DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
  13.     }
  14.     );
  15.     GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
  16.  
  17.   }
  18. }

  2. 日志记录 WebApiActionDebugFilter

  1. public class WebApiActionDebugFilter : System.Web.Http.Filters.ActionFilterAttribute
  2. {
  3.  
  4. /// <summary>
  5. /// 是否开启调试
  6. /// </summary>
  7. private bool _isDebugLog = (ConfigurationManager.AppSettings["isDebugLog"]) != null && ConfigurationManager.AppSettings["isDebugLog"].ToString().ToLower() == "false" ? false : true;
  8. private readonly ILog txtlog = log4net.LogManager.GetLogger("txtLogger");
  9.  
  10. public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext context)
  11. {
  12. //log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + @"xmlconfig/log4net.config"));
  13. base.OnActionExecuting(context);
  14.  
  15. if (_isDebugLog)
  16. {
  17. try
  18. {
  19. var controllerName = context.ControllerContext.ControllerDescriptor.ControllerName;
  20. var controller = context.ControllerContext.Controller.GetType();
  21. var actionName = context.ActionDescriptor.ActionName;
  22. var descr = string.Empty;
  23. var members = controller.GetMethods();
  24.  
  25. foreach (var member in members)
  26. {
  27. if (member.Name == actionName)//如果是obejct
  28. {
  29. object[] attrs = member.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);
  30. if (attrs.Length > )
  31. descr = (attrs[] as System.ComponentModel.DescriptionAttribute).Description;
  32. break;
  33. }
  34. }
  35.  
  36. var txtParams = "";
  37.  
  38. //******读流会影响图片上传的接口获取不到流了******
  39. //var task = context.Request.Content.ReadAsStreamAsync();
  40. //using (System.IO.Stream sm = task.Result)
  41. //{
  42. // if (sm != null && sm.Length > 0)
  43. // {
  44. // sm.Seek(0, SeekOrigin.Begin);
  45. // int len = (int)sm.Length;
  46. // byte[] inputByts = new byte[len];
  47. // sm.Read(inputByts, 0, len);
  48. // //sm.Close();
  49. // txtParams = Encoding.UTF8.GetString(inputByts);
  50. // }
  51. //}
  52.  
  53. if (context.Request.Method.ToString().ToLower() == "get")
  54. {
  55. txtParams = context.Request.RequestUri.Query;
  56. }
  57. else if (context.Request.Method.ToString().ToLower() == "post")
  58. {
  59. if (context.ActionArguments != null && context.ActionArguments.Count > )
  60. {
  61. txtParams = JsonConvert.SerializeObject(context.ActionArguments);
  62. }
  63. }
  64.  
  65. var beginRequestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
  66. context.Request.Content.Headers.Add("BeginRequestTime", beginRequestTime);
  67. //写文件
  68. var logInfo = new
  69. {
  70. CallTime = beginRequestTime,
  71. ActionType = "请求",
  72. ControllerName = controllerName,
  73. ActionName = actionName,
  74. Description = descr,
  75. Params = txtParams,
  76. ReqGuid = context.Request.GetCorrelationId().ToString().Replace("-", "")
  77. };
  78.  
  79. Console.WriteLine(logInfo);
  80.  
  81. Util.ExecuteInvoke(() => txtlog.Info(GetObjetJson(logInfo)));
  82. }
  83. catch (Exception ex)
  84. {
  85. var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
  86. {
  87. Content = new StringContent("请求出错,详细信息如下:"+Environment.NewLine+ex.Message),
  88. ReasonPhrase = "请求不被允许"
  89. };
  90. throw new HttpResponseException(response);
  91. //txtlog.Info("请求出错"+ ex.Message + ex.StackTrace);
  92. }
  93. }
  94. }
  95. public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext context)
  96. {
  97. base.OnActionExecuted(context);
  98.  
  99. if (_isDebugLog)
  100. {
  101. try
  102. {
  103. var controllerName = context.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
  104. var actionName = context.ActionContext.ActionDescriptor.ActionName;
  105. var txtResult = context.Response.Content.ReadAsStringAsync().Result;
  106. var endTime = DateTime.Now;
  107. var reqGuid = context.ActionContext.Request.GetCorrelationId().ToString().Replace("-", "");
  108. var beginTime = context.Request.Content.Headers.GetValues("BeginRequestTime").FirstOrDefault();
  109. var execTime = Util.ExecTimeDiff(Convert.ToDateTime(beginTime), endTime);
  110.  
  111. //写文件
  112. var logInfo = new
  113. {
  114. CallTime = endTime.ToString("yyyy-MM-dd HH:mm:ss.fff"),
  115. ExecTime = execTime,
  116. ActionType = "响应",
  117. ControllerName = controllerName,
  118. ActionName = actionName,
  119. Params = txtResult,
  120. ReqGuid = reqGuid
  121. };
  122.  
  123. Util.ExecuteInvoke(() => txtlog.Info(GetObjetJson(logInfo)));
  124. }
  125. catch (Exception ex)
  126. {
  127. txtlog.Info("响应出错" + ex.Message + ex.StackTrace);
  128. }
  129. }
  130. }
  131.  
  132. private string GetObjetJson(object message)
  133. {
  134. var retStr = "";
  135. try
  136. {
  137. if (message != null)
  138. {
  139. var json = JsonConvert.SerializeObject(message);
  140. retStr = json;
  141. //if (json != null) retStr = json.Replace("\\\"", "");
  142. }
  143. }
  144. catch (Exception)
  145. {
  146. // ignored
  147. }
  148. return retStr;
  149. }
  150. }

  3. 文件上传

  1. public class SysUpdateController : ApiController
  2. {
  3. [HttpGet]
  4. [ActionName("getfilemd5")]
  5. public HttpResponseMessage GetFileMD5(string fileName, string parentDir)
  6. {
  7. HttpResponseMessage response = new HttpResponseMessage();
  8. try
  9. {
  10. string baseDirectory = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/"), string.Format("{0}\\", parentDir));
  11. fileName = Path.Combine(baseDirectory, fileName);
  12. string content = "";
  13. if (!File.Exists(fileName))
  14. {
  15. content = "未知错误";
  16. }
  17. else
  18. {
  19. content = GetMD5HashFromFile(fileName);
  20. }
  21. response.Content = new StringContent(content, System.Text.Encoding.UTF8, "text/json");
  22. response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  23. }
  24. catch (Exception ex)
  25. {
  26. response.Content = new StringContent("未知错误:" + ex.Message, System.Text.Encoding.UTF8, "text/json");
  27. response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  28. }
  29. return response;
  30. }
  31. [HttpGet]
  32. [ActionName("getpackage")]
  33. public HttpResponseMessage GetPackage()
  34. {
  35. HttpResponseMessage response = new HttpResponseMessage();
  36. try
  37. {
  38. string baseDirectory = System.Web.Hosting.HostingEnvironment.MapPath("~/");
  39. string filePath = Path.Combine(baseDirectory, "QCPackage\\");
  40. string[] files = Directory.GetFiles(filePath);
  41.  
  42. if (files.Length > )
  43. {
  44. filePath = files[];
  45. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  46. response.Content = new StreamContent(fileStream);
  47. response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
  48. response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(filePath);
  49. // 这句话要告诉浏览器要下载文件
  50. response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  51. response.Content.Headers.ContentLength = new FileInfo(filePath).Length;
  52. }
  53. else
  54. {
  55. response.Content = new StringContent("未知错误", System.Text.Encoding.UTF8, "text/json");
  56. response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  57. }
  58. }
  59. catch
  60. {
  61. response.Content = new StringContent("未知错误", System.Text.Encoding.UTF8, "text/json");
  62. response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  63. }
  64. return response;
  65. }
  66.  
  67. /// <summary>
  68. /// 文件下载
  69. /// </summary>
  70. /// <param name="filePath "></param>
  71. /// <returns></returns>
  72. [HttpGet]
  73. [ActionName("getfiles")]
  74. public HttpResponseMessage GetFiles(string parentDir)
  75. {
  76. HttpResponseMessage response = new HttpResponseMessage();
  77. try
  78. {
  79. List<string> files = new List<string>();
  80. string baseDirectory = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/"), string.Format("{0}\\", parentDir));
  81. string[] rootPathFiles = Directory.GetFiles(baseDirectory);
  82. files.AddRange(rootPathFiles);
  83. string[] rootPathDirectories = Directory.GetDirectories(baseDirectory);
  84. foreach (string directory in rootPathDirectories)
  85. {
  86. GetFiles(directory, files);
  87. }
  88. for (int i = ; i < files.Count; i++)
  89. {
  90. files[i] = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(files[i].Replace(baseDirectory, "")));
  91. }
  92.  
  93. string content = Newtonsoft.Json.JsonConvert.SerializeObject(files);
  94. response.Content = new StringContent(content, System.Text.Encoding.UTF8, "text/json");
  95. response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  96. }
  97. catch
  98. {
  99. response.Content = new StringContent("未知错误", System.Text.Encoding.UTF8, "text/json");
  100. response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  101. }
  102. return response;
  103. }
  104.  
  105. /// <summary>
  106. /// 文件下载
  107. /// </summary>
  108. /// <param name="filePath "></param>
  109. /// <returns></returns>
  110. [HttpGet]
  111. [ActionName("upgrade")]
  112. public HttpResponseMessage Upgrade(string fileName, string parentDir)
  113. {
  114. string baseDirectory = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/"), string.Format("{0}\\", parentDir));
  115. string filePath = Path.Combine(baseDirectory, fileName);
  116.  
  117. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  118. HttpResponseMessage response = new HttpResponseMessage();
  119. response.Content = new StreamContent(fileStream);
  120. response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
  121. response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(filePath);
  122. // 这句话要告诉浏览器要下载文件
  123. response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  124. response.Content.Headers.ContentLength = new FileInfo(filePath).Length;
  125. return response;
  126. }
  127.  
  128. private void GetFiles(string filePath, List<string> files)
  129. {
  130. string[] currentPathFiles = Directory.GetFiles(filePath);
  131. string[] currentPathDirectories = Directory.GetDirectories(filePath);
  132. files.AddRange(currentPathFiles);
  133. foreach (string currentPath in currentPathDirectories)
  134. {
  135. GetFiles(currentPath, files);
  136. }
  137. }
  138.  
  139. private string GetMD5HashFromFile(string fileName)
  140. {
  141. try
  142. {
  143. FileStream file = new FileStream(fileName, FileMode.Open);
  144. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  145. byte[] retVal = md5.ComputeHash(file);
  146. file.Close();
  147.  
  148. StringBuilder sb = new StringBuilder();
  149. for (int i = ; i < retVal.Length; i++)
  150. {
  151. sb.Append(retVal[i].ToString("x2"));
  152. }
  153. return sb.ToString();
  154. }
  155. catch (Exception ex)
  156. {
  157. throw ex;
  158. }
  159. }
  160. }

  4. FTPHelper

  1. public class FTPHelper
  2. {
  3. /// <summary>
  4. /// FTP请求对象
  5. /// </summary>
  6. FtpWebRequest request = null;
  7. /// <summary>
  8. /// FTP响应对象
  9. /// </summary>
  10. FtpWebResponse response = null;
  11. /// <summary>
  12. /// FTP服务器地址
  13. /// </summary>
  14. public string ftpURI { get; private set; }
  15. /// <summary>
  16. /// FTP服务器IP
  17. /// </summary>
  18. public string ftpServerIP { get; private set; }
  19. /// <summary>
  20. /// FTP服务器默认目录
  21. /// </summary>
  22. public string ftpRemotePath { get; private set; }
  23. /// <summary>
  24. /// FTP服务器登录用户名
  25. /// </summary>
  26. public string ftpUserID { get; private set; }
  27. /// <summary>
  28. /// FTP服务器登录密码
  29. /// </summary>
  30. public string ftpPassword { get; private set; }
  31.  
  32. /// <summary>
  33. /// 初始化
  34. /// </summary>
  35. /// <param name="FtpServerIP">FTP连接地址</param>
  36. /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
  37. /// <param name="FtpUserID">用户名</param>
  38. /// <param name="FtpPassword">密码</param>
  39. public FTPHelper(string ftpServerIP, string ftpRemotePath, string ftpUserID, string ftpPassword)
  40. {
  41. this.ftpServerIP = ftpServerIP;
  42. this.ftpRemotePath = ftpRemotePath;
  43. this.ftpUserID = ftpUserID;
  44. this.ftpPassword = ftpPassword;
  45. this.ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
  46. }
  47. ~FTPHelper()
  48. {
  49. if (response != null)
  50. {
  51. response.Close();
  52. response = null;
  53. }
  54. if (request != null)
  55. {
  56. request.Abort();
  57. request = null;
  58. }
  59. }
  60. /// <summary>
  61. /// 建立FTP链接,返回响应对象
  62. /// </summary>
  63. /// <param name="uri">FTP地址</param>
  64. /// <param name="ftpMethod">操作命令</param>
  65. /// <returns></returns>
  66. private FtpWebResponse Open(Uri uri, string ftpMethod)
  67. {
  68. request = (FtpWebRequest)FtpWebRequest.Create(uri);
  69. request.Method = ftpMethod;
  70. request.UseBinary = true;
  71. request.KeepAlive = false;
  72. //request.UsePassive = false;//主动模式
  73. request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword);
  74. return (FtpWebResponse)request.GetResponse();
  75. }
  76.  
  77. /// <summary>
  78. /// 建立FTP链接,返回请求对象
  79. /// </summary>
  80. /// <param name="uri">FTP地址</param>
  81. /// <param name="ftpMethod">操作命令</param>
  82. private FtpWebRequest OpenRequest(Uri uri, string ftpMethod)
  83. {
  84. request = (FtpWebRequest)WebRequest.Create(uri);
  85. request.Method = ftpMethod;
  86. request.UseBinary = true;
  87. request.KeepAlive = false;
  88. request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword);
  89. return request;
  90. }
  91. /// <summary>
  92. /// 创建目录
  93. /// </summary>
  94. /// <param name="remoteDirectoryName">目录名</param>
  95. public void CreateDirectory(string remoteDirectoryName)
  96. {
  97. response = Open(new Uri(ftpURI + remoteDirectoryName), WebRequestMethods.Ftp.MakeDirectory);
  98. }
  99. /// <summary>
  100. /// 更改目录或文件名
  101. /// </summary>
  102. /// <param name="currentName">当前名称</param>
  103. /// <param name="newName">修改后新名称</param>
  104. public void ReName(string currentName, string newName)
  105. {
  106. request = OpenRequest(new Uri(ftpURI + currentName), WebRequestMethods.Ftp.Rename);
  107. request.RenameTo = newName;
  108. response = (FtpWebResponse)request.GetResponse();
  109. }
  110. /// <summary>
  111. /// 切换当前目录
  112. /// </summary>
  113. /// <param name="IsRoot">true:绝对路径 false:相对路径</param>
  114. public void GotoDirectory(string DirectoryName, bool IsRoot)
  115. {
  116. if (IsRoot)
  117. ftpRemotePath = DirectoryName;
  118. else
  119. ftpRemotePath += "/" + DirectoryName;
  120.  
  121. ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
  122. }
  123. /// <summary>
  124. /// 删除目录(包括下面所有子目录和子文件)
  125. /// </summary>
  126. /// <param name="remoteDirectoryName">要删除的带路径目录名:如web/test</param>
  127. /*
  128. * 例:删除test目录
  129. FTPHelper helper = new FTPHelper("x.x.x.x", "web", "user", "password");
  130. helper.RemoveDirectory("web/test");
  131. */
  132. public void RemoveDirectory(string remoteDirectoryName)
  133. {
  134. GotoDirectory(remoteDirectoryName, true);
  135. var listAll = ListFilesAndDirectories();
  136. foreach (var m in listAll)
  137. {
  138. if (m.IsDirectory)
  139. RemoveDirectory(m.Path);
  140. else
  141. DeleteFile(m.Name);
  142. }
  143. GotoDirectory(remoteDirectoryName, true);
  144. response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.RemoveDirectory);
  145. }
  146. /// <summary>
  147. /// 文件上传
  148. /// </summary>
  149. /// <param name="localFilePath">本地文件路径</param>
  150. public void Upload(string localFilePath)
  151. {
  152. FileInfo fileInf = new FileInfo(localFilePath);
  153. request = OpenRequest(new Uri(ftpURI + fileInf.Name), WebRequestMethods.Ftp.UploadFile);
  154. request.ContentLength = fileInf.Length;
  155. int buffLength = ;
  156. byte[] buff = new byte[buffLength];
  157. int contentLen;
  158. using (var fs = fileInf.OpenRead())
  159. {
  160. using (var strm = request.GetRequestStream())
  161. {
  162. contentLen = fs.Read(buff, , buffLength);
  163. while (contentLen != )
  164. {
  165. strm.Write(buff, , contentLen);
  166. contentLen = fs.Read(buff, , buffLength);
  167. }
  168. }
  169. }
  170. }
  171.  
  172. public string Upload(byte[] buff)
  173. {
  174. string fileName = DateTime.Now.ToFileTime().ToString() + ".png";
  175. string path = DateTime.Now.ToString("yyyyMM").ToString();
  176. if (!IsExist(path))
  177. CreateDirectory(path);
  178.  
  179. path += "/" + fileName;
  180.  
  181. request = OpenRequest(new Uri(ftpURI + path), WebRequestMethods.Ftp.UploadFile);
  182. using (var strm = request.GetRequestStream())
  183. {
  184. strm.Write(buff, , buff.Length);
  185. }
  186.  
  187. return path;
  188. }
  189.  
  190. /// <summary>
  191. /// 上传best64图片
  192. /// </summary>
  193. /// <param name="base64String"></param>
  194. /// <returns></returns>
  195. public string UploadBase64(string base64String)
  196. {
  197. string fileName = DateTime.Now.ToFileTime().ToString() + ".png";
  198. string path = DateTime.Now.ToString("yyyyMM").ToString();
  199. if (!IsExist(path))
  200. CreateDirectory(path);
  201.  
  202. path += "/" + fileName;
  203.  
  204. request = OpenRequest(new Uri(ftpURI + path), WebRequestMethods.Ftp.UploadFile);
  205. request.ContentLength = base64String.Length;
  206.  
  207. byte[] byteArray = Convert.FromBase64String(base64String);
  208. using (var strm = request.GetRequestStream())
  209. {
  210. strm.Write(byteArray, , byteArray.Length);
  211. }
  212.  
  213. return path;
  214. }
  215.  
  216. /// <summary>
  217. /// 下载
  218. /// </summary>
  219. /// <param name="saveFilePath">下载后的保存路径</param>
  220. /// <param name="downloadFileName">要下载的文件名</param>
  221. public void Download(string saveFilePath, string downloadFileName)
  222. {
  223. using (FileStream outputStream = new FileStream(saveFilePath + "\\" + downloadFileName, FileMode.Create))
  224. {
  225. response = Open(new Uri(ftpURI + downloadFileName), WebRequestMethods.Ftp.DownloadFile);
  226. using (Stream ftpStream = response.GetResponseStream())
  227. {
  228. long cl = response.ContentLength;
  229. int bufferSize = ;
  230. int readCount;
  231. byte[] buffer = new byte[bufferSize];
  232. readCount = ftpStream.Read(buffer, , bufferSize);
  233. while (readCount > )
  234. {
  235. outputStream.Write(buffer, , readCount);
  236. readCount = ftpStream.Read(buffer, , bufferSize);
  237. }
  238. }
  239. }
  240. }
  241.  
  242. /// <summary>
  243. /// 获取文件best64编码
  244. /// </summary>
  245. /// <param name="downloadFileName"></param>
  246. /// <returns></returns>
  247. public string DownloadBest64(string downloadFileName)
  248. {
  249. response = Open(new Uri(ftpURI + downloadFileName), WebRequestMethods.Ftp.DownloadFile);
  250. var ftpStream = response.GetResponseStream();
  251. var ms = new MemoryStream();
  252.  
  253. var bufferSize = ;
  254. var buffer = new byte[bufferSize];
  255. while ((bufferSize = ftpStream.Read(buffer, , bufferSize)) > )
  256. {
  257. ms.Write(buffer, , bufferSize);
  258. }
  259. var bast64 = Convert.ToBase64String(ms.ToArray());
  260.  
  261. return bast64;
  262. }
  263.  
  264. /// <summary>
  265. /// 删除文件
  266. /// </summary>
  267. /// <param name="remoteFileName">要删除的文件名</param>
  268. public void DeleteFile(string remoteFileName)
  269. {
  270. response = Open(new Uri(ftpURI + remoteFileName), WebRequestMethods.Ftp.DeleteFile);
  271. }
  272.  
  273. /// <summary>
  274. /// 获取当前目录的文件和一级子目录信息
  275. /// </summary>
  276. /// <returns></returns>
  277. public List<FileStruct> ListFilesAndDirectories()
  278. {
  279. var fileList = new List<FileStruct>();
  280. response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.ListDirectoryDetails);
  281. using (var stream = response.GetResponseStream())
  282. {
  283. using (var sr = new StreamReader(stream))
  284. {
  285. string line = null;
  286. while ((line = sr.ReadLine()) != null)
  287. {
  288. //line的格式如下:
  289. //08-18-13 11:05PM <DIR> aspnet_client
  290. //09-22-13 11:39PM 2946 Default.aspx
  291. DateTime dtDate = DateTime.ParseExact(line.Substring(, ), "MM-dd-yy", null);
  292. DateTime dtDateTime = DateTime.Parse(dtDate.ToString("yyyy-MM-dd") + line.Substring(, ));
  293. string[] arrs = line.Split(' ');
  294. var model = new FileStruct()
  295. {
  296. IsDirectory = line.IndexOf("<DIR>") > ? true : false,
  297. CreateTime = dtDateTime,
  298. Name = arrs[arrs.Length - ],
  299. Path = ftpRemotePath + "/" + arrs[arrs.Length - ]
  300. };
  301. fileList.Add(model);
  302. }
  303. }
  304. }
  305. return fileList;
  306. }
  307. /// <summary>
  308. /// 列出当前目录的所有文件
  309. /// </summary>
  310. public List<FileStruct> ListFiles()
  311. {
  312. var listAll = ListFilesAndDirectories();
  313. var listFile = listAll.Where(m => m.IsDirectory == false).ToList();
  314. return listFile;
  315. }
  316. /// <summary>
  317. /// 列出当前目录的所有一级子目录
  318. /// </summary>
  319. public List<FileStruct> ListDirectories()
  320. {
  321. var listAll = ListFilesAndDirectories();
  322. var listFile = listAll.Where(m => m.IsDirectory == true).ToList();
  323. return listFile;
  324. }
  325. /// <summary>
  326. /// 判断当前目录下指定的子目录或文件是否存在
  327. /// </summary>
  328. /// <param name="remoteName">指定的目录或文件名</param>
  329. public bool IsExist(string remoteName)
  330. {
  331. var list = ListFilesAndDirectories();
  332. if (list.Count(m => m.Name == remoteName) > )
  333. return true;
  334. return false;
  335. }
  336. /// <summary>
  337. /// 判断当前目录下指定的一级子目录是否存在
  338. /// </summary>
  339. /// <param name="RemoteDirectoryName">指定的目录名</param>
  340. public bool IsDirectoryExist(string remoteDirectoryName)
  341. {
  342. var listDir = ListDirectories();
  343. if (listDir.Count(m => m.Name == remoteDirectoryName) > )
  344. return true;
  345. return false;
  346. }
  347. /// <summary>
  348. /// 判断当前目录下指定的子文件是否存在
  349. /// </summary>
  350. /// <param name="RemoteFileName">远程文件名</param>
  351. public bool IsFileExist(string remoteFileName)
  352. {
  353. var listFile = ListFiles();
  354. if (listFile.Count(m => m.Name == remoteFileName) > )
  355. return true;
  356. return false;
  357. }
  358. }

从文件流读取

  1. var paths = string.Empty;
  2. var streamProvider = new MultipartMemoryStreamProvider();
  3. //var dic = new Dictionary<string, string>();
  4. await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(multipartContent =>
  5. {
  6. if (multipartContent.IsFaulted || multipartContent.IsCanceled) return;
  7.  
  8. foreach (var content in multipartContent.Result.Contents)
  9. {
  10. if (content.Headers.ContentType == null || content.Headers.ContentType.MediaType == null ||
  11. !content.Headers.ContentType.MediaType.Contains("image"))
  12. //if (string.IsNullOrEmpty(content.Headers.ContentDisposition.FileName))
  13. {
  14. //var val = content.ReadAsStringAsync().Result;
  15. //dic.Add(content.Headers.ContentDisposition.Name.Replace("\"", ""), val);
  16. }
  17. else
  18. {
  19. var bytes = content.ReadAsByteArrayAsync().Result;
  20. var path = ftp.Upload(bytes);
  21. paths += path + ",";
  22. }
  23. }
  24. });

WebAPI 笔记的更多相关文章

  1. WebApi笔记

    WebApi有一段时间没用了,这几天用webapi做了一个接口供第三方调用,又重新折腾了下,做个笔记记录下心得,防止遗忘. 1.webapi使用的RESTful风格的传参方式,其实就是充分利用HTTP ...

  2. Visual Studio 2015 Owin+MVC+WebAPI+ODataV4+EntityFrawork+Identity+Oauth2.0+AngularJS 1.x 学习笔记

    2016年,.net 会有很多大更新 ASP.NET 5 在此之前我都是用着古老的.net做开发的 (WebForm + IIS) 为了接下来应对 .net 的新功能,我特地去学习了一下基本的 MVC ...

  3. Asp.Net Core WebApi学习笔记(四)-- Middleware

    Asp.Net Core WebApi学习笔记(四)-- Middleware 本文记录了Asp.Net管道模型和Asp.Net Core的Middleware模型的对比,并在上一篇的基础上增加Mid ...

  4. 笔记-ASP.NET WebApi

    本文是针对ASP.NET WepApi 2 的笔记. Web API 可返回的结果: 1.void 2.HttpResponseMessage 3.IHttpActionResult 4.其他类型 返 ...

  5. WebAPI调用笔记 ASP.NET CORE 学习之自定义异常处理 MySQL数据库查询优化建议 .NET操作XML文件之泛型集合的序列化与反序列化 Asp.Net Core 轻松学-多线程之Task快速上手 Asp.Net Core 轻松学-多线程之Task(补充)

    WebAPI调用笔记   前言 即时通信项目中初次调用OA接口遇到了一些问题,因为本人从业后几乎一直做CS端项目,一个简单的WebAPI调用居然浪费了不少时间,特此记录. 接口描述 首先说明一下,基于 ...

  6. 路由其实也可以很简单-------Asp.net WebAPI学习笔记(一) ASP.NET WebApi技术从入门到实战演练 C#面向服务WebService从入门到精通 DataTable与List<T>相互转换

    路由其实也可以很简单-------Asp.net WebAPI学习笔记(一)   MVC也好,WebAPI也好,据我所知,有部分人是因为复杂的路由,而不想去学的.曾经见过一位程序猿,在他MVC程序中, ...

  7. ASP.Net MVC开发基础学习笔记:五、区域、模板页与WebAPI初步

    一.区域—麻雀虽小,五脏俱全的迷你MVC项目 1.1 Area的兴起 为了方便大规模网站中的管理大量文件,在ASP.NET MVC 2.0版本中引入了一个新概念—区域(Area). 在项目上右击创建新 ...

  8. 【笔记】Asp.Net WebApi对js POST带参数跨域请求的支持方案

    先说下需求:在原来的WebApi项目中增加对js跨域的请求支持,请求方式:以POST为主,webapi路由规则根据原项目需求修改如下: public static void Register(Http ...

  9. 【读书笔记】WebApi 和 SPA(单页应用)--knockout的使用

    Web API从MVC4开始出现,可以服务于Asp.Net下的任何web应用,本文将介绍Web api在单页应用中的使用.什么是单页应用?Single-Page Application最常用的定义:一 ...

随机推荐

  1. SQL优化 | Oracle 绑定变量

    之前整理过一篇有关绑定变量的文章,不太详细,重新补充一下. Oracle 绑定变量 http://www.cndba.cn/Dave/article/1275 一.绑定变量 bind variable ...

  2. word excel 未响应

    前几天笔记本突然出现word 一打开就未响应的情况,导致完全无法使用.今天发现 excel 也出现了这种情况.今天终于下定决心解决这个问题. 百度上搜索了很多,找到了很多解决方案.总结如下. 一.禁用 ...

  3. opencv之调用摄像头

    基础知识 # cap.set(propId, value) # 设置视频参数: propId - 设置的视频参数, value - 设置的参数值 # cap.isOpened() 返回 true/fa ...

  4. 009-多线程-JUC集合-Queue-LinkedBlockingDeque

    一.概述 LinkedBlockingDeque是双向链表实现的双向并发阻塞队列.该阻塞队列同时支持FIFO和FILO两种操作方式,即可以从队列的头和尾同时操作(插入/删除):并且,该阻塞队列是支持线 ...

  5. flutter showDatePicker显示中文日期_Flutter时间控件显示中文

    flutter showDatePicker showTimePicker显示中文日期 1.配置flutter_localizations依赖 找到pubspec.yaml配置flutter_loca ...

  6. 阶段5 3.微服务项目【学成在线】_day18 用户授权_07-动态查询用户权限-权限数据模型

    3 动态查询用户权限 3.1 需求分析 截至目前在测试授权时使用的权限数据是静态数据,正常情况的流程是: 1.管理员给用户分配权限,权限数据写到数据库中. 2.认证服务在进行用户认证时从数据库读取用户 ...

  7. Apache三种工作模式详解

    Apache HTTP服务器被设计为一个强大的.灵活的能够在多种平台以及不同环境下工作的服务器.这种模块化的设计就叫做“多进程处理模块”(Multi-Processing Module,MPM),也叫 ...

  8. Spring Aop(十五)——Aop原理之Advised接口

    转发地址:https://www.iteye.com/blog/elim-2398726 Spring Aop原理之Advised接口 通过之前我们介绍的ProxyFactory我们知道,Spring ...

  9. SQLAlchemy相关文档

    目录 参考文档 一.执行原生SQL语句 1.实例一 2.实例二 2.实例三 二.ORM操作 1.创建数据库表 (1)创建单表 (2)创建多个表并包含FK.M2M关系 2.操作数据库表 (1)基于sco ...

  10. tp5博客项目实战2

    改虚拟主机 (用www.tp5.com直接访问替代localhost/blog/tp5/public) 1.host修改 位置C:\Windows\System32\drivers\etc 127.0 ...