简体   繁体   中英

Attribute authorisation in ASP.NET MVC 5

I have the following class in my Models folder

namespace School.Models
{
        public enum Grade
        {
            A, B, C, D, F
        }

        public class Enrollment
        {
            public int EnrollmentID { get; set; }
            public int CourseID { get; set; }
            public int StudentID { get; set; }
            public Grade Grade { get; set; }

            public virtual Course Course { get; set; }
            public virtual Student Student { get; set; }
        }
}

I want to make authorisation in the Grade attribute so when a Admin Role log in the Admin can modify the grade value and when a User Role log in, the User can not modify the attribute and only see the value of the grade (and how do I make a default value for the grade attribute)

Add the authorize attribute over the controller action that updates the grade.

[Authorize(Roles = "user or group")]
    public IActionResult UpdateGrade()
    {
        //update grade  here

        return View();
    }

Set the default grade in the class constructor.

public class Enrollment
{

    public Enrollment()
    {
        Grade = Grade.B;
    }

    public int EnrollmentID { get; set; }
    public int CourseID { get; set; }
    public int StudentID { get; set; }
    public Grade Grade { get; set; }

    public virtual Course Course { get; set; }
    public virtual Student Student { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM