控制器:
using LoginDemo.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using WebApplication4.Models;
namespace LoginDemo.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private UserabcContext db = new UserabcContext();
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(ILogger<HomeController> logger, IHostingEnvironment hostingEnvironment)
{
_logger = logger;
_hostingEnvironment = hostingEnvironment;
}
public IActionResult Index()
{
return View();
}
// //验证方法
public static string VerificationCodeCacheFormat = "vcode_cache_{0}";
public IActionResult ValidateCode()
{
VerificationCodeServices _vierificationCodeServices = new VerificationCodeServices();
string code = "";
System.IO.MemoryStream ms = _vierificationCodeServices.Create(out code);
code = code.ToLowerInvariant();//验证码不分大小写
HttpContext.Session.SetString("SupportValidateCode", code);
Response.Body.Dispose();
var token = Guid.NewGuid().ToString();
Response.Cookies.Append("validatecode", token);
return File(ms.ToArray(), @"image/png");
}
public IActionResult IzUserVoder(string userVerCode)
{
if (VerifyUserInputCode(userVerCode))
{
HttpContext.Session.SetString("SupportValidateCode", "");
return Json(1);
}
return Json(0);
}
/// <summary>
/// 验证码判断
/// </summary>
/// <param name="userVerCode"></param>
/// <returns></returns>
public bool VerifyUserInputCode(string userVerCode)
{
string vCode = HttpContext.Session.GetString("SupportValidateCode");
if (vCode != userVerCode) return false;
return true;
}
public ResonpeData<AddUser> Login(string Account, string Pwd)
{
ResonpeData<AddUser> resonpe = new ResonpeData<AddUser>();
if (string.IsNullOrEmpty(Account))
{
resonpe.code = 0;
resonpe.msg = "请输入账号";
resonpe.data = new AddUser { };
return resonpe;
}
if (string.IsNullOrEmpty(Pwd))
{
resonpe.code = 0;
resonpe.msg = "请输入密码";
resonpe.data = new AddUser { };
return resonpe;
}
AddUser data = db.AddUsers.Where(p => p.Account == Account.Trim()
&& p.Pwd == Pwd.Trim()).FirstOrDefault();
if (data == null)
{
resonpe.code = 0;
resonpe.msg = "账号或密码错误";
resonpe.data = new AddUser { };
return resonpe;
}
HttpContext.Session.SetString("account", data.Account);
resonpe.code = 1;
resonpe.msg = "登录成功";
resonpe.data = new AddUser { };
return resonpe;
}
public IActionResult list()
{
//ResonpeData<List<DataList>> resonpe = new ResonpeData<List<DataList>>();
List<Appdd> data = db.Appdds.ToList();
if (HttpContext.Session.GetString("account") == null || HttpContext.Session.GetString("account") == "")
{
return RedirectToAction("index", "home");
}
ViewBag.Account = HttpContext.Session.GetString("account");
return View(data);
}
public IActionResult add()
{
if (HttpContext.Session.GetString("account") == null || HttpContext.Session.GetString("account") == "")
{
return RedirectToAction("index", "home");
}
ViewBag.Account = HttpContext.Session.GetString("account");
return View();
}
public IActionResult save(IFormFile formFile, Appdd appdd)
{
if (HttpContext.Session.GetString("account") == null || HttpContext.Session.GetString("account") == "")
{
return RedirectToAction("index", "home");
}
ViewBag.Account = HttpContext.Session.GetString("account");
string path = "";
var currentDate = DateTime.Now;
var webRootPath = _hostingEnvironment.WebRootPath;//>>>相当于HttpContext.Current.Server.MapPath("")
try
{
var filePath = $"/img/{currentDate:yyyyMMdd}/";
//创建每日存储文件夹
if (!Directory.Exists(webRootPath + filePath))
{
Directory.CreateDirectory(webRootPath + filePath);
}
if (formFile != null)
{
//文件后缀
var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式,拓展名
//判断文件大小
var fileSize = formFile.Length;
if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
{
return new JsonResult(new { isSuccess = false, resultMsg = "上传的文件不能大于10M" });
}
//保存的文件名称(以名称和保存时间命名)
var saveName = formFile.FileName.Substring(0, formFile.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;
//文件保存
using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
{
formFile.CopyTo(fs);
fs.Flush();
}
//完整的文件路径 /img/
var completeFilePath = Path.Combine(filePath, saveName);
path = completeFilePath;
ViewBag.img = path;
}
else
{
return new JsonResult(new { isSuccess = false, resultMsg = "上传失败,未检测上传的文件信息~" });
}
}
catch (Exception ex)
{
return new JsonResult(new { isSuccess = false, resultMsg = "文件保存失败,异常信息为:" + ex.Message });
}
if (appdd.AppId !=null )
{
//修改
Appdd data = db.Appdds.Where(p=>p.AppId==appdd.AppId).FirstOrDefault();
if (data != null)
{
// //data.AppId = appdd.AppId;
// data.Appnmae = appdd.Appnmae;
// data.Lnpayh = appdd.Lnpayh;
// data.Lmagepath = path;
// data.PuTime = appdd.PuTime;
// data.Description = appdd.Description;
string sql=$"update Appdd set APPNmae = '{appdd.Appnmae}', Lnpayh = '{appdd.Lnpayh}', lmagepath = '{path}', puTime = '{appdd.PuTime}',[Description] = '{appdd.Description}' where AppID = '{appdd.AppId}'";
db.Database.ExecuteSqlRawAsync(sql);
}
db.SaveChanges();
}
else
{
try
{
//新增
string sql = $"insert Appdd values('{ Guid.NewGuid()}','{appdd.Appnmae}','{appdd.Lnpayh}','{path}','{appdd.PuTime}','{appdd.Description}','') ";
db.Database.ExecuteSqlRawAsync(sql);
}
catch (Exception ex)
{
throw ex;
}
}
return RedirectToAction("list");
}
public IActionResult exit()
{
if (HttpContext.Session.GetString("account") == null || HttpContext.Session.GetString("account") == "")
{
return RedirectToAction("index", "home");
}
ViewBag.Account = HttpContext.Session.GetString("account");
HttpContext.Session.SetString("account", "");
return RedirectToAction("index", "home");
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
index
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<form method="post" id="frmLogin">
<div class="form-group">
<label for="exampleInputEmail1">用户名:</label>
<input type="text" class="form-control" id="Account" name="Account">
</div>
<div class="form-group">
<label for="exampleInputPassword1">密码:</label>
<input type="password" class="form-control" id="Pwd" name="Pwd">
</div>
<div>
验证码:<input type="text" id="validateCode" class="col-form-label-sm" />
<img id="imgVerify" src="~/Home/ValidateCode" alt="看不清?点击更换" onclick="this.src = this.src + '?'" style="vertical-align:middle;" />
</div>
<br />
<span id="code" style="color:red"></span>
<br /><br />
<button type="button" class="btn btn-primary" onclick="addPush();login()">登录</button>
</form>
</div>
<script>
function login() {
let account = $("#Account").val();
let pwd = $("#Pwd").val();
$.ajax({
url: "/home/login",
type: "post",
data: { Account: account, Pwd: pwd},
dataType: 'json',
success: function (data) {
alert(data.msg);
if (data.code == 0) {
window.location.href = "/home/index"
} else {
window.location.href = "/home/list"
}
}
});
}
</script>
@section Scripts{
<script type="text/javascript">
$(function () {
});
var str = "?";
function addPush() {
$.ajax({
url: 'Home/IzUserVoder',
dataType: 'JSON',
type: 'POST',
data: {
userVerCode:
$("#validateCode").val()
},
success: function (date) {
if (date == "0") {
$("#imgVerify").attr("src", "Home/ValidateCode" + str)
$("#validateCode").val("");
$("#code").css("color", "red");
$("#code").html("验证码不正确");
str += str;
return false;
}
$("#code").css("color", "black");
$("#code").html("验证码正确");
document.getElementById("frmLogin").submit();
}
})
}
</script>
}
list
@{
ViewData["Title"] = "list";
}
@model List<Appdd>
<div class="form-group row">
<label for="staticEmail">用户名: @ViewBag.Account</label>
<a href="/home/add">新增</a>
<a href="/home/exit">退出登录</a>
</div>
<div class="container">
<div class="row">
<div class="col-6">
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div>
<ul class="nav navbar-nav">
@foreach (var item in Model)
{
<li class="row" onclick="show('@item.AppId', '@item.Appnmae', '@item.Lnpayh','@item.Lmagepath', '@item.PuTime', '@item.Description')">
<img src="@item.Lmagepath" id="img" class="img-thumbnail" style="height: 70px;">
<a>@item.Appnmae</a>
</li>
}
</ul>
</div>
</div>
</nav>
</div>
<div class="col-6" id="main">
<form enctype="multipart/form-data" method="post" action="/home/save">
<div class="form-group">
<label for="exampleInputPassword1">标题</label>
<input type="text" class="projectfile" id="APPNmae" name="APPNmae">
<input type="hidden" class="projectfile" id="AppId" name="AppId">
</div>
<div class="form-group">
<label for="exampleInputPassword1">访问地址</label>
<input type="text" class="projectfile" id="Lnpayh" name="Lnpayh">
</div>
<div class="form-group">
<label for="exampleInputPassword1">图片</label>
<input type="file" class="projectfile" id="formFile" name="formFile">
<img src="" id="image" style="height: 70px;" />
</div>
<div class="form-group">
<label for="exampleInputPassword1">时间</label>
<input type="text" class="projectfile" id="puTime" name="puTime">
</div>
<div class="form-group">
<label for="exampleInputPassword1">描述</label>
<input type="text" class="projectfile" id="Description" name="Description">
</div>
<div class="form-group">
<label for="exampleInputPassword1">pdf</label>
<input type="file" class="projectfile" id="UserManual" name="UserManual">
</div>
<button class="btn btn-primary" onclick="conceal()">保存</button>
<hr style="width:100px" />
</form>
</div>
</div>
</div>
<script>
window.onload = function () {
$("#main").hide();//隐藏
}
function conceal() {
$("#main").hide();//隐藏
}
function show(AppId, Appnmae, Lnpayh, Lmagepath, PuTime, Description) {
alert(1);
$("#main").show();//显示
$("#APPNmae").val(Appnmae);
$("#AppId").val(AppId);
$("#Lnpayh").val(Lnpayh);
$("#image").attr("src", Lmagepath);
$("#puTime").val(PuTime);
$("#Description").val(Description);
}
</script>
add
@{
ViewData["Title"] = "add";
}
<form enctype="multipart/form-data" method="post" action="/home/save">
<div class="form-group row">
<label for="staticEmail">用户名: @ViewBag.Account</label>
</div>
<div class="form-group">
<label for="exampleInputPassword1">标题</label>
<input type="text" class="projectfile" id="Appnmae" name="Appnmae">
</div>
<div class="form-group">
<label for="exampleInputPassword1">访问地址</label>
<input type="text" class="projectfile" id="Lnpayh" name="Lnpayh">
</div>
<div class="form-group">
<label for="exampleInputPassword1">图片</label>
<input type="file" class="projectfile" id="formFile" name="formFile">
<img src="" id="image" style="height: 70px;" />
</div>
<div class="form-group">
<label for="exampleInputPassword1">时间</label>
<input type="text" class="projectfile" id="puTime" name="puTime">
</div>
<div class="form-group">
<label for="exampleInputPassword1">描述</label>
<input type="text" class="projectfile" id="Description" name="Description">
</div>
<button class="btn btn-primary">保存</button>
<hr style="width:100px" />
</form>
sql数据库验证是否可以:
insert Appdd values(newid(),'火车','www.baidu.com','~/src/1.jpg','2021','2','')
insert Appdd values('968038b7-e627-4b80-b3e5-ca5d478c6bf8','起床','www.baidu.com','/img/20211101/4_205222.jpg','2021','11','')
update Appdd set APPNmae='1',Lnpayh='1',lmagepath='1',puTime='2021',[Description]='' where AppID='968038b7-e627-4b80-b3e5-ca5d478c6bf8'
整体sql代码
create table Appdd(
AppID uniqueidentifier,--编号
APPNmae nvarchar(50) null,--标题
Lnpayh nvarchar(500) null,--访问地址
lmagepath nvarchar(500) null,--图片
puTime datetime null,--时间
Description nvarchar(2000) null,--描述
UserManual nvarchar(500) null,--pdf
)
CREATE TABLE addUser(
Id int IDENTITY(1,1) NOT NULL,
Account nvarchar(50) NULL,
Pwd nvarchar(50) NULL
)
insert into addUser(Account, Pwd)VALUES('admin','123')
INSERT INTO Appdd (AppID,APPNmae, Lnpayh, lmagepath, puTime, Description, UserManual) VALUES (newid(),N'ABCDEFG',N'http://www.add.com',N'img/20211030/批注 2020-05-28 194842_185359.png',N'2020-1-1',N'ADFAFAFAFAAFADFCDVFEFESESGVSG',N'新建文件夹/dd.pdf')
INSERT INTO Appdd (AppID,APPNmae, Lnpayh, lmagepath, puTime, Description, UserManual) VALUES (newid(),N'ABCDEFG',N'http://www.add.com',N'img/20211030/批注 2020-05-28 194842_185359.png',N'2020-1-1',N'ADFAFAFAFAAFADFCDVFEFESESGVSG',N'新建文件夹/dd.pdf')
INSERT INTO Appdd (AppID,APPNmae, Lnpayh, lmagepath, puTime, Description, UserManual) VALUES (newid(),N'ABCDEFG',N'http://www.add.com',N'img/20211030/批注 2020-05-28 194842_185359.png',N'2020-1-1',N'ADFAFAFAFAAFADFCDVFEFESESGVSG',N'新建文件夹/dd.pdf')
INSERT INTO Appdd (AppID,APPNmae, Lnpayh, lmagepath, puTime, Description, UserManual) VALUES (newid(),N'ABCDEFG',N'http://www.add.com',N'img/20211030/批注 2020-05-28 194842_185359.png',N'2020-1-1',N'ADFAFAFAFAAFADFCDVFEFESESGVSG',N'新建文件夹/dd.pdf')
INSERT INTO Appdd (AppID,APPNmae, Lnpayh, lmagepath, puTime, Description, UserManual) VALUES (newid(),N'ABCDEFG',N'http://www.add.com',N'img/20211030/批注 2020-05-28 194842_185359.png',N'2020-1-1',N'ADFAFAFAFAAFADFCDVFEFESESGVSG',N'新建文件夹/dd.pdf')
如果是图片路径不一样就根据图片的文件夹去获取
验证码在model中创建VerificationCodeServices
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Ef.SqlServer.com.Models
{
/// <summary>
/// 图片验证码
/// </summary>
public class VerificationCodeServices
{
/// <summary>
/// 生成指定长度的随机字符串
/// </summary>
/// <param name="codeLength">字符串的长度</param>
/// <returns>返回随机数字符串</returns>
private string RndomStr(int codeLength)
{
string chars = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] charArray = chars.Split(new Char[] { ',' });
string code = "";
int temp = -1;
Random rand = new Random();
for (int i = 1; i < codeLength + 1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
}
int t = rand.Next(61);
if (temp == t)
{
return RndomStr(codeLength);
}
temp = t;
code += charArray[t];
}
return code;
}
/// <summary>
/// 将生成的字符串写入图像文件
/// </summary>
/// <param name="code">验证码字符串</param>
/// <param name="length">生成位数(默认4位)</param>
public MemoryStream Create(out string code, int length = 4)
{
code = RndomStr(length);
Bitmap Img = null;
Graphics graphics = null;
MemoryStream ms = null;
Random random = new Random();
Color[] color = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
Img = new Bitmap((int)code.Length * 18, 32);
graphics = Graphics.FromImage(Img);
graphics.Clear(Color.White);
for (int i = 0; i < 100; i++)
{
int x = random.Next(Img.Width);
int y = random.Next(Img.Height);
graphics.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
}
for (int i = 0; i < code.Length; i++)
{
int colorIndex = random.Next(7);
int fontIndex = random.Next(4);
Font font = new Font(fonts[fontIndex], 15, FontStyle.Bold);
Brush brush = new SolidBrush(color[colorIndex]);
int y = 4;
if ((i + 1) % 2 == 0)
{
y = 2;
}
graphics.DrawString(code.Substring(i, 1), font, brush, 3 + (i * 12), y);
}
ms = new MemoryStream();
Img.Save(ms, ImageFormat.Png);
graphics.Dispose();
Img.Dispose();
return ms;
}
}
}