Azure Active Directory(ASP.NET MVC 项目)入门Getting Started with Azure Active Directory (ASP.NET MVC Projects)

本文提供通过 Visual Studio 的“项目”>“连接的服务” 命令将 Active Directory 添加到 ASP.NET MVC 项目后的其他指南。This article provides additional guidance after you've added Active Directory to an ASP.NET MVC project through the Project > Connected Services command of Visual Studio. 如果尚未将该服务添加到你的项目,可以随时执行该操作。If you've not already added the service to your project, you can do so at any time.

请参阅我的 MVC 项目发生了什么情况?,了解添加连接服务时对项目所做的更改。See What happened to my MVC project? for the changes made to your project when adding the connected service.

访问控制器需要身份验证Requiring authentication to access controllers

项目中的所有控制器均带有 [Authorize] 属性。All controllers in your project were adorned with the [Authorize] attribute. 此属性要求用户先进行身份验证,然后才能访问这些控制器。This attribute requires the user to be authenticated before accessing these controllers. 若要允许匿名访问控制器,请从控制器删除此属性。To allow the controller to be accessed anonymously, remove this attribute from the controller. 如果想要更详细地设置这些权限,请将该属性应用到需要身份验证的每个方法,而不是将它应用到控制器类。If you want to set the permissions at a more granular level, apply the attribute to each method that requires authorization instead of applying it to the controller class.

添加 SignIn/SignOut 控件Adding SignIn / SignOut Controls

若要将 SignIn/SignOut 控件添加到视图,可使用 _LoginPartial.cshtml 分部视图将该功能添加到某个视图。To add the SignIn/SignOut controls to your view, you can use the _LoginPartial.cshtml partial view to add the functionality to one of your views. 下面是已添加到标准 _Layout.cshtml 视图的功能示例。Here is an example of the functionality added to the standard _Layout.cshtml view. (注意带有 navbar-collapse 类的 div 中的最后一个元素):(Note the last element in the div with class navbar-collapse):

<!DOCTYPE html>
     <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
    <div class="container body-content">
        <hr />
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
    @RenderSection("scripts", required: false)

后续步骤Next steps