-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathUserController.cs
More file actions
82 lines (79 loc) · 2.88 KB
/
Copy pathUserController.cs
File metadata and controls
82 lines (79 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NetCoreBBS.Interfaces;
using NetCoreBBS.Entities;
using Microsoft.AspNetCore.Authorization;
using NetCoreBBS.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using System.IO;
namespace NetCoreBBS.Controllers
{
[Authorize]
public class UserController : Controller
{
private ITopicRepository _topic;
private ITopicReplyRepository _reply;
private UserManager<User> UserManager;
private IWebHostEnvironment _env;
public UserController(ITopicRepository topic, ITopicReplyRepository reply, UserManager<User> userManager, IWebHostEnvironment env)
{
_topic = topic;
_reply = reply;
UserManager = userManager;
_env = env;
}
public IActionResult Index()
{
var u = UserManager.GetUserAsync(User).Result;
var topics = _topic.List(r => r.UserId == u.Id).ToList();
var replys = _reply.List(r => r.ReplyUserId == u.Id).ToList();
ViewBag.Topics = topics;
ViewBag.Replys = replys;
return View(u);
}
public IActionResult Edit()
{
return View(UserManager.GetUserAsync(User).Result);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(UserViewModel usermodel)
{
var user = UserManager.GetUserAsync(User).Result;
if (ModelState.IsValid)
{
if (usermodel.Avatar != null)
{
var avatar = usermodel.Avatar;
if (avatar.Length / 1024 > 100)
{
return Content("Í·ÏñÎļþ´óС³¬¹ý100KB");
}
var ext = Path.GetExtension(avatar.FileName);
var avatarfile = user.Id + ext;
var avatarpath = Path.Combine(_env.WebRootPath, "images", "avatar");
if (!Directory.Exists(avatarpath))
Directory.CreateDirectory(avatarpath);
var filepath = Path.Combine(avatarpath, avatarfile);
using (FileStream fs = new FileStream(filepath, FileMode.Create))
{
avatar.CopyTo(fs);
fs.Flush();
}
user.Avatar = $"/images/avatar/{avatarfile}";
}
user.Email = usermodel.Email;
user.Url = usermodel.Url;
user.GitHub = usermodel.GitHub;
user.Profile = usermodel.Profile;
await UserManager.UpdateAsync(user);
return RedirectToAction("Index");
}
return View(user);
}
}
}