ASP.NET Web API 튜 토리 얼 생 성 Admin 보기 상세 설명

7621 단어 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 요청 을 보 내 는 방식 으로 이 페이지 는 사용자 가 제품 을 만 들 거나 편집 하거나 삭제 할 수 있 도록 해 준다.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 방법 은 웹 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-type 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 functional is wired up yet.'추가'를 누 르 면 Admin.cshtml 이라는 파일 을 Views/Home 에 추가 합 니 다.이 파일 을 열 고 다음 HTML 을 추가 합 니 다.이 HTML 은 페이지 의 구 조 를 정 의 했 지만 연결 기능 이 없습니다.Create a Link to the Admin Page Admin 페이지 에 만 든 링크 In Solution Explorer,expand the Views folder and then expand the Shared folder.Open the file namedLayout.cshtml.Locate the ul element with id="menu",and an action link for the Admin view:"솔 루 션 자원 관리자"에서 Views 폴 더 를 펼 친 다음 Shared 폴 더 를 엽 니 다.이름 열기Layout.cshtml 파일 입 니 다.id="menu"의 ul 요소 와 Admin 보기에 사용 할 동작 링크 를 찾 습 니 다
 
<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>
In the sample project,I made a few other cosmetic changes,such as replacing the string"Your logo here".These don't affect the functional of the application.You can download the project and compare the files.이 예 항목 에서,나 는 문자열'Your logo here(이것 은 당신 의 로고 입 니 다)'를 바 꾸 는 등 몇 가지 다른 장식 적 인 수정 을 했 습 니 다.이것 은 이 프로그램의 기능 에 영향 을 주지 않 을 것 이다.이 항목 을 다운로드 하고 이 파일 을 비교 할 수 있 습 니 다.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 access 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 폴 더 를 펼 치고 Initialize Simple Membership Attribute.cs 라 는 파일 을 열 어 Simple Membership Initializer 구조 로 찾 습 니 다.웹 보안.Initialized DatabaseConnection 호출 후 다음 코드 를 추가 합 니 다
 
<li>@Html.ActionLink("Admin", "Admin", "Home")</li>
This is a quick-and-dirty way to add the"Administrator"role and create a user for the role.이것 은"Administrator"역할 을 추가 하고 이 역할 에 사용 자 를 만 드 는 빠 르 고 직접적인 방식 입 니 다.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 방법 에 추가 합 니 다
 
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);
}
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 를 사용 하고 웹 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 요청 을 보 내 면 인증 쿠키 를 포함해 야 합 니 다.그렇지 않 으 면 서버 에서 HTTP 401(인증 되 지 않 음)응답 을 보 냅 니 다.Fiddler 에서 하 나 를 보 냅 니 다.http://localhost:port/api/admin라 는 GET 요청 을 하면 이런 상황 을 볼 수 있다.

좋은 웹페이지 즐겨찾기