ASP.NET Web API教程 建立Admin視圖詳細介紹

來源:互聯網
上載者:User

Now we'll turn to the client side, and add a page that can consume data from the Admin controller. The page will allow users to create, edit, or delete products, by sending AJAX requests to the controller.
現在我們轉入用戶端,並添加一個能夠使用從Admin控制器而來的資料的頁面。通過給控制器發送AJAX請求的方式,該頁面將允許使用者建立、編輯,或刪除產品。
In Solution Explorer, expand the Controllers folder and open the file named HomeController.cs. This file contains an MVC controller. Add a method named Admin:
在“方案總管”中,展開Controllers檔案夾,並開啟名為HomeController.cs的檔案。這個檔案是一個MVC控制器。添加一個名稱為Admin的方法: 複製代碼 代碼如下:public ActionResult Admin()
{
string apiUri= Url.HttpRouteUrl("DefaultApi", new { controller = "admin", });
ViewBag.ApiUrl = new Uri(Request.Url, apiUri).AbsoluteUri.ToString();
return View();
}

The HttpRouteUrl method creates the URI to the web API, and we store this in the view bag for later.
HttpRouteUrl方法建立了發送給Web API的URI,我們隨後把它儲存在視圖包(view bag)中。
Next, position the text cursor within the Admin action method, then right-click and select Add View. This will bring up the Add View dialog.
下一步,把文本游標定位到Admin動作方法的內部,然後右擊,並選擇“添加視圖”。這會帶出“添加視圖”對話方塊(見圖2-20)。

圖2-20. 添加視圖
In the Add View dialog, name the view "Admin". Select the check box labeled Create a strongly-typed view. Under Model Class, select "Product (ProductStore.Models)". Leave all the other options as their default values.
在“添加視圖”對話方塊中,將此視圖命名為“Admin”。選中標籤為“建立強型別視圖”的複選框。在“模型類”下面,選擇“Product (ProductStore.Models)”。保留所有其它選項為其預設值(2-21)。

圖2-21. “添加視圖”對話方塊的設定
Clicking Add adds a file named Admin.cshtml under Views/Home. Open this file and add the following HTML. This HTML defines the structure of the page, but no functionality is wired up yet.
點擊“添加”,會把一個名稱為Admin.cshtml的檔案添加到Views/Home下。開啟這個檔案,並添加以下HTML。這個HTML定義了頁面的結構,但尚未串連功能。 複製代碼 代碼如下:<div class="content">
<div class="float-left">
<ul id="update-products">
<li>
<div><div class="item">Product ID</div><span></span></div>
<div><div class="item">Name</div> <input type="text" /></div>
<div><div class="item">Price ($)</div> <input type="text" /></div>
<div><div class="item">Actual Cost ($)</div> <input type="text" /></div>
<div>
<input type="button" value="Update" />
<input type="button" value="Delete Item" />
</div>
</li>
</ul>
</div>
<div class="float-right">
<h2>Add New Product</h2>
<form id="product">
@Html.ValidationSummary(true)
<fieldset>
<legend>Contact</legend>
@Html.EditorForModel()
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
</form>
</div>
</div>

Create a Link to the Admin Page
建立到Admin頁面的連結
In Solution Explorer, expand the Views folder and then expand the Shared folder. Open the file named _Layout.cshtml. Locate the ul element with id = "menu", and an action link for the Admin view:
在“方案總管”中,展開Views檔案夾,然後展開Shared檔案夾。開啟名稱為_Layout.cshtml的檔案。定位到id = "menu"的ul元素,和一個用於Admin視圖的動作連結: 複製代碼 代碼如下:<li>@Html.ActionLink("Admin", "Admin", "Home")</li>

In the sample project, I made a few other cosmetic changes, such as replacing the string “Your logo here”. These don't affect the functionality of the application. You can download the project and compare the files.
在這個例子項目中,我做了幾個其它裝飾性的修改,如替換了字串“Your logo here(這是你的logo)”。這些不會影響此應用程式的功能。你可以下載這個項目並比較此檔案。
Run the application and click the “Admin” link that appears at the top of the home page. The Admin page should look like the following:
運行該應用程式,並點擊出現在首頁頂部的這個“Admin”連結。Admin頁面看上去應當像這樣(見圖2-22):

圖2-22. Admin頁面
Right now, the page doesn't do anything. In the next section, we'll use Knockout.js to create a dynamic UI.
此刻,這個頁面不做任何事情。在下一小節中,我們將使用Knockout.js來建立一個動態UI。
Add Authorization
添加授權
The Admin page is currently accessible to anyone visiting the site. Let's change this to restrict permission to administrators.
Admin此刻可以被任何訪問網站的人所訪問。讓我們做點修改,把許可限制到管理員。
Start by adding an "Administrator" role and an administrator user. In Solution Explorer, expand the Filters folder and open the file named InitializeSimpleMembershipAttribute.cs. Locate the SimpleMembershipInitializer constructor. After the call to WebSecurity.InitializeDatabaseConnection, add the following code:
先從添加“Administrator(管理員)”角色和administrator使用者開始。在“方案總管”中,展開Filters檔案夾,並開啟名稱為InitializeSimpleMembershipAttribute.cs的檔案,定位到SimpleMembershipInitializer構造器。在對WebSecurity.InitializeDatabaseConnection的調用之後,添加以下代碼: 複製代碼 代碼如下: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 http://localhost:port/api/admin.
現在,只有管理員才可以查看Admin頁面。而且,如果對Admin控制器發送一個HTTP請求,該請求必須包含一個認證cookie。否則,伺服器會發送一個HTTP 401(未授權)響應。在Fiddler中,通過發送一個http://localhost:port/api/admin的GET請求,便會看到這種情況。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.