ASP.NET Web API教程 创建Admin视图详细介绍(2)


const string adminRole = "Administrator";
const string adminName = "Administrator";
if (!Roles.RoleExists(adminRole))
{
Roles.CreateRole(adminRole);
}
if (!WebSecurity.UserExists(adminName))
{
WebSecurity.CreateUserAndAccount(adminName, "password");
Roles.AddUserToRole(adminName, adminRole);
}


This is a quick-and-dirty way to add the "Administrator" role and create a user for the role.
这是添加“Administrator”角色并为该角色创建用户的一种快速而直接的方式。
In Solution Explorer, expand the Controllers folder and open the HomeController.cs file. Add the Authorize attribute to the Admin method.
在“解决方案资源管理器”中,展开Controllers文件夹,并打开HomeController.cs文件。把Authorize(授权)注解属性添加到Admin方法上:

复制代码 代码如下:


[Authorize(Roles="Administrator")]
public ActionResult Admin()
{
return View();
}Open the AdminController.cs file and add the Authorize attribute to the entire AdminController class.
打开AdminController.cs文件,并把Authorize注解属性添加到整个AdminController类上:
[Authorize(Roles="Administrator")]
public class AdminController : ApiController
{
// ...


MVC and Web API both define Authorize attributes, in different namespaces. MVC uses System.Web.Mvc.AuthorizeAttribute, while Web API uses System.Web.Http.AuthorizeAttribute.
MVC和Web API都定义了Authorize注解属性,但位于不同的命名空间。MVC使用的是System.Web.Mvc.AuthorizeAttribute,而Web API使用System.Web.Http.AuthorizeAttribute。
Now only administrators can view the Admin page. Also, if you send an HTTP request to the Admin controller, the request must contain an authentication cookie. If not, the server sends an HTTP 401 (Unauthorized) response. You can see this in Fiddler by sending a GET request to :port/api/admin.
现在,只有管理员才可以查看Admin页面。而且,如果对Admin控制器发送一个HTTP请求,该请求必须包含一个认证cookie。否则,服务器会发送一个HTTP 401(未授权)响应。在Fiddler中,通过发送一个:port/api/admin的GET请求,便会看到这种情况。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjdxfs.html