.Net Core MVC实现自己的AllowAnonymous

全局过滤,在Startup中ConfigureServices里面添加如下代码
  services.AddMvc(options =>
                {
                    options.Filters.Add(typeof(MyActionFilterAttribute));
                }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
MyActionFilterAttribute的实现
public class MyActionFilterAttribute : ActionFilterAttribute
    {



        public override void OnActionExecuting(ActionExecutingContext context)
        {

            var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            if (controllerActionDescriptor != null)
            {
              
                var isDefined = controllerActionDescriptor.ControllerTypeInfo.GetCustomAttributes(inherit: true)
                    .Any(a => a.GetType().Equals(typeof(NoActionFilterAttribute)));

                if (!isDefined)
                {
                  //业务逻辑
                    base.OnActionExecuting(context);
                }
            }

        

        }
    }
NoActionFilterAttribute
    public class NoActionFilterAttribute : Attribute
    {
    }
在不需要验证的Controller上打上NoActionFilter特性即可
   [NoActionFilter]
    public class TestController : Controller
    {
    
    }

转载于:https://www.cnblogs.com/aishangyipiyema/p/9881654.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
.NET 中,可以使用 ASP.NET Identity 实现用户注册和登录。以下是基本步骤: 1. 创建 ASP.NET MVC/Web API 项目。 2. 在 Visual Studio 中打开“解决方案资源管理器”,然后右键单击“引用”并选择“管理 NuGet 程序包”。 3. 在“NuGet 程序包管理器”中搜索“Microsoft.AspNet.Identity.Core”和“Microsoft.AspNet.Identity.EntityFramework”。 4. 安装这两个包后,右键单击“Models”文件夹,选择“添加新项”,然后选择“数据”>“ADO.NET 实体数据模型”。 5. 在“Entity 数据模型向导”中选择“从数据库生成模型”,然后选择数据库连接字符串并选择要使用的表。 6. 在“生成模型向导”中,选择要包含在模型中的表和列,然后单击“完成”。 7. 在“Models”文件夹中创建一个名为“ApplicationUser.cs”的新类,并从“IdentityUser”类继承。 8. 打开“Startup.cs”文件并添加以下代码: ```csharp using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(YourProjectNamespace.Startup))] namespace YourProjectNamespace { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } } ``` 9. 在“App_Start”文件夹中创建一个名为“IdentityConfig.cs”的新类,并添加以下代码: ```csharp using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using YourProjectNamespace.Models; namespace YourProjectNamespace { public class ApplicationUserManager : UserManager<ApplicationUser> { public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) { } public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); return manager; } } public class ApplicationSignInManager : SignInManager<ApplicationUser, string> { public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) : base(userManager, authenticationManager) { } public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context) { return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication); } } } ``` 10. 在“App_Start”文件夹中创建一个名为“Startup.Auth.cs”的新类,并添加以下代码: ```csharp using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Owin; using YourProjectNamespace.Models; namespace YourProjectNamespace { public partial class Startup { public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext(() => new ApplicationDbContext()); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); } } } ``` 11. 在“Controllers”文件夹中创建一个名为“AccountController.cs”的新类,并添加以下代码: ```csharp using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using YourProjectNamespace.Models; namespace YourProjectNamespace.Controllers { public class AccountController : Controller { private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public AccountController() { } public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) { UserManager = userManager; SignInManager = signInManager; } public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } } [AllowAnonymous] public ActionResult Register() { return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToAction("Index", "Home"); } AddErrors(result); } return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return RedirectToAction("Index", "Home"); } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } return RedirectToAction("Index", "Home"); } private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } } } ``` 12. 在“Views”文件夹中创建一个名为“Account”文件夹,并创建以下视图: - Login.cshtml - Register.cshtml 13. 运行应用程序并访问“/Account/Register”以注册新用户。然后访问“/Account/Login”以登录。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值