【ASP.NET Web API教程】2.3.4 创建Admin视图

简介: 原文:【ASP.NET Web API教程】2.3.4 创建Admin视图注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。 Part 4: Adding an Admin View 第4部分:添加Admin视图 本文引自:http://www.
原文: 【ASP.NET Web API教程】2.3.4 创建Admin视图

注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。

Part 4: Adding an Admin View
第4部分:添加Admin视图

本文引自:http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/using-web-api-with-entity-framework,-part-4

Add an Admin View
添加Admin视图

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)。

WebAPI2-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)。

WebAPI2-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):

WebAPI2-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请求,便会看到这种情况。


看完此文如果觉得有所收获,请给个推荐

目录
相关文章
|
20天前
|
JSON 数据可视化 API
Python 中调用 DeepSeek-R1 API的方法介绍,图文教程
本教程详细介绍了如何使用 Python 调用 DeepSeek 的 R1 大模型 API,适合编程新手。首先登录 DeepSeek 控制台获取 API Key,安装 Python 和 requests 库后,编写基础调用代码并运行。文末包含常见问题解答和更简单的可视化调用方法,建议收藏备用。 原文链接:[如何使用 Python 调用 DeepSeek-R1 API?](https://apifox.com/apiskills/how-to-call-the-deepseek-r1-api-using-python/)
|
10天前
|
人工智能 API 开发工具
【重磅发布】 免费领取阿里云百炼AI大模型100万Tokens教程出炉,API接口实战操作,DeepSeek-R1满血版即刻体验!
阿里云百炼是一站式大模型开发及应用构建平台,支持开发者和业务人员轻松设计、构建大模型应用。通过简单操作,用户可在5分钟内开发出大模型应用或在几小时内训练专属模型,专注于创新。
336 87
【重磅发布】 免费领取阿里云百炼AI大模型100万Tokens教程出炉,API接口实战操作,DeepSeek-R1满血版即刻体验!
|
2月前
|
开发框架 前端开发 JavaScript
ASP.NET Web Pages - 教程
ASP.NET Web Pages 是一种用于创建动态网页的开发模式,采用HTML、CSS、JavaScript 和服务器脚本。本教程聚焦于Web Pages,介绍如何使用Razor语法结合服务器端代码与前端技术,以及利用WebMatrix工具进行开发。适合初学者入门ASP.NET。
|
13天前
|
机器学习/深度学习 人工智能 Serverless
👉「免费满血DeepSeek实战-联网搜索×Prompt秘籍|暨6平台横评」
满血 DeepSeek 免费用!支持联网搜索!创作声明:真人攥写-非AI生成,Written-By-Human-Not-By-AI
2112 9
👉「免费满血DeepSeek实战-联网搜索×Prompt秘籍|暨6平台横评」
|
21天前
|
缓存 自然语言处理 安全
快速调用 Deepseek API!【超详细教程】
Deepseek 强大的功能,在本教程中,将指导您如何获取 DeepSeek API 密钥,并演示如何使用该密钥调用 DeepSeek API 以进行调试。
|
15天前
|
监控 Linux PHP
【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
65 20
|
22天前
|
存储 人工智能 安全
如何调用 DeepSeek-R1 API ?图文教程
首先登录 DeepSeek 开放平台,创建并保存 API Key。接着,在 Apifox 中设置环境变量,导入 DeepSeek 提供的 cURL 并配置 Authorization 为 `Bearer {{API_KEY}}`。通过切换至正式环境发送请求,可实现对话功能,支持流式或整体输出。
1485 15
|
1月前
|
开发框架 数据可视化 .NET
.NET 中管理 Web API 文档的两种方式
.NET 中管理 Web API 文档的两种方式
48 14
|
2月前
|
网络协议 API
检测指定TCP端口开放状态免费API接口教程
此API用于检测指定TCP端口是否开放,支持POST/GET请求。需提供用户ID、KEY、目标主机,可选指定端口(默认80)和地区(默认国内)。返回状态码、信息提示、检测主机、端口及状态(开放或关闭)。示例中ID和KEY为公共测试用,建议使用个人ID和KEY以享受更高调用频率。
81 14
|
2月前
|
API
获取网页状态码[可指定地域]免费API接口教程
该接口用于获取指定网址的访问状态码,支持从国内、香港、美国等地域节点访问。通过POST或GET请求,需提供用户ID、KEY及目标网址等参数。返回结果包括状态码和信息提示。 示例:https://cn.apihz.cn/api/wangzhan/getcode.php?id=88888888&key=88888888&type=1&url=www.apihz.cn。

热门文章

最新文章