/************************ExceptionFilter.cs***********************************/
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Filters
{
public class ExceptionFilter:ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
context.Result = new ContentResult() { Content = "系统发生错误"};
}
}
}
/************************************************************************/
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using WebApplication1.Filters;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController:Controller
{
[ResourceFilter]
[ActionFilter]
[ExceptionFilter]
public IActionResult Index()
{
throw new Exception("发生错误");
//return View();
//return Content("hello");
//int d = 1 + 1;
//return View(d);
UserModel user = new UserModel() { Name = "zhangsan" };
return View(user);
}
public IActionResult Login()
{
return Content("登录");
}
public IActionResult DoLogin()
{
string token = "123456";
string name = "zhangsan";
ClaimsIdentity identity = new ClaimsIdentity("Forms");
identity.AddClaim(new Claim(ClaimTypes.Sid, token));
identity.AddClaim(new Claim(ClaimTypes.Name, name));
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
return Content("登录成功");
}
[Authorize(AuthenticationSchemes =CookieAuthenticationDefaults.AuthenticationScheme)]
public IActionResult Center()
{
string token = User.FindFirstValue(ClaimTypes.Sid);
return Content("Center");
}
}
}