Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write a shared disk file Web viewer for Asp.Net Core

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article shows you how to write a shared disk file Web viewer by Asp.Net Core. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the details of this article.

Viewer function description and demonstration

The main purpose of this viewer is to make it easy for you to view the logs on the server. Other security issues are not considered here, such as logging in by specific personnel, which you need to add. If your server has ip open to the public, it is recommended to consider configuring it as an ip in your company's private network when running this software. Some security problems can be avoided here. Here are the main features:

. Configure common disk access addresses by defining files

. View folders and files under the disk directory

. Some accessible line files (such as txt,DLL, pictures, etc.) can be opened or downloaded in the browser (accessibility format is configured by the program)

. Upload multiple files to the specified disk

. File backup (if the uploaded file already exists, it will be automatically backed up to the bak folder)

Effect gif picture, a little flower, a lot of tolerance:

The effect is all right.

Disk list function

First of all, it is clear that api already corresponds to most framwork in NetCore1.1 (according to a blog post of @ Friends, NetCore2.0 's api has been on a par with framwork), so here we can directly use DirectoryInfo to check the folders and files of the disk path, so we have the code to check the list Action:

1 / / 2 / / disk list 3 / 4 / / disk path 5 / 6 public IActionResult Index (string path) 7 {8 Console.WriteLine ($"IP: {HttpContext.Connection.RemoteIpAddress} viewing disk: {path}"); 9 var list = new List () 10 MoSearch moSerach = new MoSearch {Txt1 = path}; 11 ViewData ["Search"] = moSerach;12 13 if (string.IsNullOrWhiteSpace (path)) {return View (list);} 14 if (path.StartsWith ("c:", StringComparison.OrdinalIgnoreCase)) {this.MsgBox ($"No permission access: {path}"); return View (list) } 15 if (! System.IO.Directory.Exists (path)) {this.MsgBox ($"disk path: {path} does not exist!") ; return View (list);} 16 DirectoryInfo dic = new DirectoryInfo (path); 17 list = dic.GetFileSystemInfos (). OrderByDescending (b = > b.LastWriteTime). ToList (); 18 19 return View (list); 20}

Here, I limit disk C by default, and use the self-contained file object FileSystemInfo to return information. You only need a segment dic.GetFileSystemInfos (). OrderByDescending (b = > b.LastWriteTime). ToList () to obtain the disk directory information according to the latest modification time. The corresponding View layout is as follows:

1 @ using System.IO 2 @ using ShenNiu.LogTool.Extension; 3 @ using ShenNiu.LogTool.Controllers 4 @ model List 5 @ {6 ViewData ["Title"] = "log search"; 7 8 var moSearch = ViewData ["Search"] as MoSearch 9} 10 11 @ ViewData ["Title"] 12 13 14 15 disk path 16 17 18 19 Common address 20 21 @ * = Please select = 22 23 D:\ D\ Joke 24 25 26 D disk 27 * @ 28 29 30 31 32 33 34 Enquiry 35 upload 36 return 37 38 @ ViewData ["msg"] 39 40 41 42 43 44 45 filename 46 disk path 47 Last Update time 48 creation time 49 Operation 50 51 52 53 @ foreach (var item in Model) 54 {55 56 57 @ if (item.Attributes = = FileAttributes.Archive) 58 {59

@ item.Name 60} 61 else if (item.Attributes = = FileAttributes.Directory) 62 {63

@ item.Name 64} 65 else 66 {67

@ item.Name 68} 69 @ item.Attributes 70 71 @ item.FullName 72 @ item.LastWriteTime 73 @ item.CreationTime 74 75 @ if (item.Attributes = = FileAttributes.Archive) 76 {77 View 78} 79 80 81} 82 83 84 @ ViewData ["msg"] 85 86 87 $(function () {88 89 $("# btnUp"). On ("click") Function () {90 var msg = $("# span01") 91 var form = document.getElementById ("form01"); 92 / / console.log (form); 93 var data = new FormData (form) 94 95 $.ajax ({96 type: "POST", 97 url: "/ log/AjaxFileUp", 98 data: data, 99 100 contentType: false,101 processData: false 102 success: function (data) {103 if (data) {104 msg.html (data.msg) Error: function () {108 msg.html ("upload file is abnormal, please try again later!") 112113 $("# btnSearch") .on ("click", function () {114115 var sel1Val = $.trim ($("select [name = 'sel1'] option:selected") .val ()); 116var txt1Val = $.trim ($("# txt1") .val ()) 117 118 119 var pathVal = sel1Val.length b.Name = = "upFile"); 17 / / non-empty limit 18 if (files = = null | | files.Count ()! allowType.Contains (b.ContentType)) 23 / / {24 / / data.Msg = $"only files in {string.Join (", ", allowType)} format can be uploaded." ; 25 / / return Json (data); 26 / /} 27 28 / / size limit 29 var nMax = 20 30 if (files.Sum (b = > b.Length) > = 1024 * 1024 * nMax) 31 {32 data.Msg = $"the total size of uploaded files can only be less than {nMax} M." ; return Json (data); 33} 34 35 / Delete files backed up in the past 36 var basePath = Path.Combine (Directory.GetCurrentDirectory (), "wwwroot", "tempbak"); 37 DirectoryInfo dic = new DirectoryInfo (basePath); 38 var nCount = dic.GetFiles (). Count (); 39 var nMaxCount = 10 40 if (nCount > nMaxCount) / / empty the temporary directory 41 {42 foreach (var item in dic.GetFiles (). OrderBy (b = > b.LastWriteTime). Take (nCount-nMaxCount)) 43 {44 try45 {46 Item.Delete () 47} 48 catch (Exception ex) {} 49} 50} 51 52 / / write to server disk 53 var upLog = new StringBuilder (string.Empty) 54 foreach (var file in files) 55 {56 57 var fileName = file.FileName;58 var path = Path.Combine (upPath, fileName); 59 upLog.AppendFormat ("File: {0};", path) 60 61 / / existing files need to be backed up 62 if (System.IO.File.Exists (path)) 63 {64 FileInfo info = new FileInfo (path); 65 var tempPath = Path.Combine (basePath, info.Name) / / backup directory 66 var newInfo = info.CopyTo (tempPath, true); 67 if (newInfo = = null) {upLog.Append ($"backup: failed, please try again later!") 68 else {upLog.Append ($"backup: success!") ;} 69} 70 71 using (var stream = System.IO.File.Create (path)) 72 {73 await file.CopyToAsync (stream); 74} 75 upLog.Append ($"upload: successful;") 76} 77 data.Msg = upLog.ToString (); 78 data.Status = 2 HttpContext.Connection.RemoteIpAddress 79} 80 catch (Exception ex) 81 {82 data.Msg + = ex.Message;83} 84 Console.WriteLine ($"IP: {HttpContext.Connection.RemoteIpAddress} uploading: {data.Msg}") 85 return Json (data); 86}

The logic code of the key points has been annotated, so I won't say much about it here, mainly for our business: upload + backup. As for the uploaded js code that has been tried in the list above, I won't repeat it here. Several custom entity classes are used here:

1 / / 2 / / Interface uniform class 3 / 4 public class MoData 5 {6 public string Msg {get; set;} 7 8 public int Status {get; set;} 9} 10 11 / 12 / search class 13 / 14 public class MoSearch25 {16 public string Txt1 {get; set;} 17 18 public string Sel1 {get; set } 19} 20 21 / / 22 / / File 23 / / 24 public class MoFile25 {26 public string Name {get; set;} 27 public string Path {get; set;} 28 public string Url {get; set;} 29 public string Content {get; set;} 30 public FileAttributes Attributes {get; set;} 31} View the content directly

The system can directly view files with suffixes such as txt,log, because this type of files generally operate simultaneously, so the way I use here is to copy the currently accessed files to the temp temporary directory, and then read or download the files. When the setting of more than 10 files is met, the files with the least modification time are deleted automatically to avoid the cost of disk space caused by the increasing copy of files. Here is the content of reading Action:

1 / 2 / / View content 3 / 4 / 5 / 6 public async Task Read (string path) 7 {8 Console.WriteLine ($"IP: {HttpContext.Connection.RemoteIpAddress} viewing file: {path}"); 9 10 var moFile = new MoFile {Path = path} 11 if (string.IsNullOrWhiteSpace (path)) {this.MsgBox ($"File path: {path} does not exist.") ; return View (moFile);} 12 if (! System.IO.File.Exists (path)) {this.MsgBox ($"File path: {path} does not exist!") ; return View (moFile);} 13 14 try15 {16 FileInfo info = new FileInfo (path); 17 / / if (! ExtensionClass._AllowExtension.Any (b = > b.ToUpper () = = info.Extension.ToUpper () 18 / / {19 / / this.MsgBox ($"cannot access the file of {info.Extension}") Return View (moFile); 20 / /} 21 22 var basePath = Path.Combine (Directory.GetCurrentDirectory (), "wwwroot", "temp"); 23 DirectoryInfo dic = new DirectoryInfo (basePath); 24 var nCount = dic.GetFiles (). Count (); 25 var nMaxCount = 10 26 if (nCount > nMaxCount) / / empty the temporary directory 27 {28 foreach (var item in dic.GetFiles (). OrderBy (b = > b.LastWriteTime). Take (nCount-nMaxCount)) 29 {30 try31 {32 Item.Delete () 33} 34 catch (Exception ex) {} 35} 36} 37 38 var tempPath = Path.Combine (basePath, info.Name); 39 var newInfo = info.CopyTo (tempPath, true) 40 if (newInfo = = null) {this.MsgBox ($"File: {path} failed to view, please try again later!") ; return View (moFile);} 41 42 moFile.Name = newInfo.Name;43 moFile.Url = $"/ {moFile.Name}"; 44 moFile.Attributes = newInfo.Attributes 45 if (moFile.Attributes = = FileAttributes.Archive & &! ExtensionClass._FileExtension.Any (b = > b = = newInfo.Extension) 46 {47 using (var stream = newInfo.OpenRead ()) 48 {49 using (var reader = new StreamReader (stream)) 50 { 51 moFile.Content = await reader.ReadToEndAsync () 52} 53} 54} 55} 56 catch (Exception ex) 57 {58 this.MsgBox ($"File: {path} failed to view, please try again later!") ; 59} 60 return View (moFile); 61} how to use the ShenNiu.LogTool tool

I only provide a running exe package ShenNiu.LogTool for windows x64 platform (no need to install any running environment). Just double-click "ShenNiu.LogTool.exe"-"configure Ip+ port (default IP:127.0.0.1, port: 12345):

-"enter: http://127.0.0.1:12345/Log in the browser to access and view the system, and the rest of the operation is like the gif screenshot above.

Use nssm tools to convert exe generated by NetCore into windows services

At this point, I would like to talk about a tool nssm (download address is not provided here, individual search bar), because as far as windows platform is concerned, if netcore generation is not published without iis, then most of it is run through exe, but it is impossible for us to open many black screen cmd-like forms on the server, so every time the server is shut down, the service will not be available. Therefore, we use nssm to transfer the exe uploaded by netcore to the windows service, so that even if the computer is shut down and restarted, it can be started in time.

Since the windows service will not prompt us to enter the bound ip and port, we need to change the code here:

1 public static void Main (string [] args) 2 {3 Encoding.RegisterProvider (CodePagesEncodingProvider.Instance); 4 Console.OutputEncoding = Encoding.GetEncoding ("GB2312"); 5 6 / / Console.WriteLine ("enter Ip bound to the service:"); 7 / / var strHost = Console.ReadLine (); if (string.IsNullOrWhiteSpace (strHost)) {strHost = "127.0.0.1" } 8 / / Console.WriteLine ("enter service bound port:"); 9 / / var strPort = Console.ReadLine (); if (string.IsNullOrWhiteSpace (strPort)) {strPort = "12345";} 10 11 / / var hostAndPort = $"http://{strHost}:{strPort}";12 var hostAndPort =" http://127.0.0.1:12345"; " 13 14 var host = new WebHostBuilder () 15 .UseKestrel () 16 .UseUrls (hostAndPort) 17 .UseContentRoot (Directory.GetCurrentDirectory ()) 18 .UseIISIntegration () 19 .UseStartup () 20 .UseApplicationInsights () 21 .B uild (); 22 23 host.Run () 24}

Then using the nssm tool, first execute the following command through the cmd command:

After execution, a box pops up, and then operate as shown in the figure:

Click "install server" again, and if nothing happens, a successful prompt will pop up. Let's take a look at the services we registered in the windows service:

At this time, the service is not started, so we can start it directly through the operation interface (of course, we can also start it through the nssm command). If there is no problem, we can visit: http://127.0.0.1:12345/Log in the browser:

The above is how Asp.Net Core writes a shared disk file Web viewer. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report