dotNetCore v2-异常过滤器

/************************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");
        }
    }
}
 

dotNetCore v2-异常过滤器dotNetCore v2-异常过滤器 dxm809 发布了406 篇原创文章 · 获赞 69 · 访问量 27万+ 他的留言板 关注
上一篇:菜鸟的自我修炼——阿里巴巴一道笔试题浅谈


下一篇:A1018 Public Bike Management (30分)