[Web API series] 1.3-practice: use ASP. NET Web API and Angular. js to create a single page application (on)

Source: Internet
Author: User
Tags actionlink

[Web API series] 1.3-practice: use ASP. NET Web API and Angular. js to create a single page application (on)

In traditional web applications, the client (browser) initiates communication with the server through the request page. The server then processes the request and sends the HTML page to the client. In subsequent operations on the page, for example, a user navigating to a link or submitting a form containing data, a new request is sent to the server and the data stream is restarted: the server processes the request and sends the new page to the browser to respond to the new action request from the client.

In a single page application (SPA), the entire page is loaded in the browser after the request is initiated, but subsequent interactions are carried out through Ajax requests. This means that after some page changes, the browser only needs to update, instead of re-loading. SPA reduces the response time of applications to user actions, thus creating a smooth experience.

In this hands-on experiment, you will use the advantages of these advanced technologies to implement Geek Quiz, a website based on the SPA concept. You will first use ASP. NET Web APIs to implement the service layer to expose the required operations to retrieve questions and store answers. Then, you will use AngularJS and CSS3 transformation effects to build a variety of UIS.

Review Gains

In this hands-on experiment, you will learn:
1. Create an ASP. NET Web API service to send and accept JSON data.
2. Use AngularJS to create the response UI
3. Use CSS3 changes to enhance the UI experience


The following are required to complete this experiment:
Visual Studio Express 2013 for Web or more advanced versions


To run this project in this hands-on experiment, you need to install the development environment first:
1. Open the resource manager and jump to the Source folder of lab's.
2. Right-click Setup. cmd and select Run as administrator to Run the installation program. This will configure your development environment and install Visual Studio code snippets (code snippet) for this experiment ).
3. If the user control window is displayed, confirm the operation.
Note: before running the installation, make sure that you have checked the dependencies required for this experiment.

Use code snippets

You are prompted to insert code blocks everywhere in the experiment document. For convenience, all the Code is provided through Visual Studio Code Snippets, which allows you to read the Code under Visual Studio 2013 without manual work.

Note: Each exercise is accompanied by the START solution in the Begin folder of the exercise, which allows you to complete each exercise separately. You need to know that the piece of code that you add during the exercise may be lost in the Start solution or cannot work before you finish the exercise. In the source code of each exercise, you will also find an End folder for the Visual Studio solution that contains the remaining steps required to complete the corresponding contact. If you need additional help in completing this hands-on experiment, you can use these solutions as a guide.


This hands-on experiment includes the following exercises:
1. Creating a Web API
2, Creating a SPA Interface

Expected completion time: 60 minutes

Note: When you start Visual Studio for the first time, you must select a predefined setting. Each predefined definition is designed to match different development styles, and determines the form layout, Editor behavior, SMART awareness of code slices, and dialog box options. When the General Development Settings set is used, action descriptions are provided during the experiment to help complete the specified task in Visual Studio. If you select different settings for your development environment, you should consider that there may be differences in the following steps.

Exercise 1: create a Web API

The service layer is a key part of SPA. It can process Ajax requests sent from the UI and return data in response to calls. The returned data must be in the machine-readable format, so that the data can be parsed and used by the client.

The Web API framework is part of the ASP. NET stack and is designed to implement HTTP services more easily. Generally, it sends and receives data in JSON or XML format through RESTful APIs. In this exercise, you will create a Web site to host the Geek Quiz application, and then use ASP. NET Web API to implement background services to expose and maintain data of the Knowledge Contest (quiz.

Task 1: Create an initial project for Geek Quiz

In this task, you will create a new ASP. net mvc project that supports ASP. NET Web APIs based on the One ASP. NET project type of Visual Studio. One ASP. NET combines all ASP. NET technologies and gives you the right to freely match and choose. You will add the template class of the Entity Framework and the database with the quiz problem.

Open Visual Stuio Express 2013 for Web and SELECT File | New Project... Create a new solution.
In the New Project dialog box, select ASP. NET Web Application under the Visual C # "Web node. Make sure you have selected. NET Framework and named it GeekQuiz. Select a Location and click OK.
In the New ASP. NET Project dialog box, select the MVC template and select the Web API option. Make sure that the Authentication option is set to the Individual User Account. Click OK to continue.

In Solution Explorer, right-click the Models file of the GeekQuiz project and select Add "Existing Item...

In the Add Existing Item dialog box, navigate to the Source/Assets/Model folder and select all files. Click Add.

Note: by adding these files, you actually add the data model, Entity Framework database context, and database initialization class to the Geek Quiz application.

Entity Framework (EF) is an object relationship ing that allows you to create database access by replacing relational storage programming with abstract application model programming.

The following describes the classes you just added:

TriviaOption: represents a single option TriviaQues corresponding to the quiz question: represents a quiz question and the option TriviaAnswer related to the question is exposed through the Options attribute: represents the TriviaContext option selected for a quiz problem: represents the Entity Framework database context of the Geek Quiz application. This class inherits from DContext and exposes the DbSet attribute, which indicates the object set described above. TriviaDatabaseInitializer: the Entity Framework initialization function is implemented by inheriting from CreateDatabaseIfNotExists as the TriviaContext class. The default behavior of this class is to create it if the database does not exist, and insert the object in the Seed method.

6. Open the Global. asax. cs file and add the following using statement.

using GeekQuiz.Models;

7. Add the following code at the beginning of the Application_Start method, which sets TriviaDatabaseInitializer to the database initializer.

public class MvcApplication : System.Web.HttpApplication{    protected void Application_Start()    {        System.Data.Entity.Database.SetInitializer(new TriviaDatabaseInitializer());         AreaRegistration.RegisterAllAreas();        GlobalConfiguration.Configure(WebApiConfig.Register);        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);        RouteConfig.RegisterRoutes(RouteTable.Routes);        BundleConfig.RegisterBundles(BundleTable.Bundles);    }}

8. Modify the Home controller to restrict user authentication. Open the HomeController. cs file in the Controller folder and add the Authorize attribute to the definition of the HomeController class.

namespace GeekQuiz.Controllers{    [Authorize]    public class HomeController : Controller    {        public ActionResult Index()        {            return View();        }        ...    }}

Note: The Authorize Filter checks whether the user is authenticated. If the user is not authenticated, it will return the HTTP Status Code 401 (Unauthorized) without performing user operations. You can apply the filter to the global, controller-level, or independent operation level.

9 now you should modify the web page layout and binding. Open the _ Layout. cshtml file in the Views | Shared folder, and update the content of the title element by modifying My ASP. NET Application to Geek Quiz.

   @ Styles. Render ("~ /Content/css ") @ Scripts. Render ("~ /Bundles/modernizr ") 

10. In the same file, remove the About and Contact links and rename the Home link to Play to update the navigation bar. In addition, change the Applicaiton name link to Geek Quiz. The HTML code in the navigation bar should look like the following:

            @Html.ActionLink("Geek Quiz", "Index", "Home", null, new { @class = "navbar-brand" })                            
  • @Html.ActionLink("Play", "Index", "Home")

11. replace My ASP. NET Application with Geek Quiz to update the footer node of the page layout. Use the following highlighted code to modify

Element Content:



© @DateTime.Now.Year - Geek Quiz

Task 2: create a Web API named TriviaController

In the previous task, you have created the initial structure of the Geek Quiz web application. Now you need to build a simple Web API service to interact with quiz's data model and expose the following actions:
GET/api/trivia: extracts the authenticated user's next question from the quiz list for the user to answer
POST/api/trivia: stores quiz answers for authenticated users one by one
You will use the ASP. NET support tool provided by Visual Studio to create baselines for the Web API controller class.
1. Open the WebApiConfig. cs file in the App_Start folder. This file defines the configuration items of the Web API service, such as how the routing maps to the action of the Web API controller.
2. Add the following using statement to the file header.

using Newtonsoft.Json.Serialization;

3. Add the following highlighted code in the Register Method to globally configure the JSON data format returned by the Web API action method.

public static class WebApiConfig{    public static void Register(HttpConfiguration config)    {        // Web API configuration and services        // Use camel case for JSON data.        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();        // Web API routes        config.MapHttpAttributeRoutes();        config.Routes.MapHttpRoute(            name: "DefaultApi",            routeTemplate: "api/{controller}/{id}",            defaults: new { id = RouteParameter.Optional }        );    }}

Note: CamelCasePropertyNamesContractResolver automatically converts the attribute name to the camel type, which is the simple name of the attribute in JavaScript.
4. In Solution Explorer, right-click the Controller folder of the GeekQuiz project and select Add | New Scaffolded Item...

5. In the Add Scaffold dialog box, make sure that the Common node on the left panel is selected. Select the Web API 2 Controller-Empty template in the middle panel and click Add.

Note: ASP. NET Scafolding is an ASP. NET Web application code generation framework. Visual Studio 2013 includes pre-installed code generators for MVC and Web API projects. When you want to quickly add code that interacts with the data model to reduce the time required for developing standard data operations, you can use scaffolding in the project ).

Scaffolding also ensures that all dependencies in the project are installed. For example.. NET project, and then use the support to add the Web API controller. The related Web API NuGet package and reference will be automatically added to your project.

6. In the Add Controller dialog box, type TriviaController in the Controller name text box and click Add.

After 7, the TriviaController. cs file is added to the Controller folder of the GeekQuiz project and contains an empty TriviaController class. Add the following using statement at the beginning of the file.

using System.Data.Entity;using System.Threading;using System.Threading.Tasks;using System.Web.Http.Description;using GeekQuiz.Models;

8. Add the following code at the beginning of the TriviaController class to define, initialize, and configure the TriviaContext instance in the controller.

public class TriviaController : ApiController{    private TriviaContext db = new TriviaContext();    protected override void Dispose(bool disposing)    {        if (disposing)        {            this.db.Dispose();        }        base.Dispose(disposing);    }}

Note: TriviaController implements the TriviaContext instance's Dispose method, which ensures that all resources used by context objects are released when the TriviaContext instance is created or garbage collection occurs. This also includes database connections opened by Entity Framework.

9 Add the following helper method at the end of the TrivialController class. This method extracts the quiz question from the database to answer the question.

private async Task
    NextQuestionAsync(string userId){    var lastQuestionId = await this.db.TriviaAnswers        .Where(a => a.UserId == userId)        .GroupBy(a => a.QuestionId)        .Select(g => new { QuestionId = g.Key, Count = g.Count() })        .OrderByDescending(q => new { q.Count, QuestionId = q.QuestionId })        .Select(q => q.QuestionId)        .FirstOrDefaultAsync();    var questionsCount = await this.db.TriviaQuestions.CountAsync();    var nextQuestionId = (lastQuestionId % questionsCount) + 1;    return await this.db.TriviaQuestions.FindAsync(CancellationToken.None, nextQuestionId);}

10 Add the following Get action methods to the TrivialController class. The method of this action calls the NextQuestionAsync method defined in the previous step to retrieve the next question for the authenticated user.

// GET api/Trivia[ResponseType(typeof(TriviaQuestion))]public async Task
    Get(){    var userId = User.Identity.Name;    TriviaQuestion nextQuestion = await this.NextQuestionAsync(userId);    if (nextQuestion == null)    {        return this.NotFound();    }    return this.Ok(nextQuestion);}

11 Add the following helper method to the TriviaController class.

private async Task
    StoreAsync(TriviaAnswer answer){    this.db.TriviaAnswers.Add(answer);    await this.db.SaveChangesAsync();    var selectedOption = await this.db.TriviaOptions.FirstOrDefaultAsync(o => o.Id == answer.OptionId        && o.QuestionId == answer.QuestionId);    return selectedOption.IsCorrect;}

12 Add the following Post action methods to the TriviaController class. This action method associates the answer with the authenticated user and calls the StoreAsync method. Then, it sends a response containing a Boolean Variable Based on the returned value of the help method.

// POST api/Trivia[ResponseType(typeof(TriviaAnswer))]public async Task
    Post(TriviaAnswer answer){    if (!ModelState.IsValid)    {        return this.BadRequest(this.ModelState);    }    answer.UserId = User.Identity.Name;    var isCorrect = await this.StoreAsync(answer);    return this.Ok

13 Add the Authorize attribute to the triviacontorler class definition to modify the Web API controller to restrict access to authenticated users.

[Authorize]public class TriviaController : ApiController{    ...}

Task 3: Running Solution

In this task, you will verify whether the Web API service you re-created in the previous Task works as expected. You will use F12 Developer Tools of Internet Explorer to capture network data transmission and detect all responses of Web API services.

Note: Make sure that the Start button on the Visual Studio toolbar is selected as Internet Explorer.

1. Press F5 to run the solution. The Log in page should appear in the browser.
Note: When an application is started, the default MVC route is triggered. It is mapped to the Index action of the HomeController class by default. Because HomeController is restricted to authenticated users (you have added the Authorize attribute to this class in Exercise 1), and no user has been authenticated yet, therefore, the application sends the original request to the logon page.

2. Click Register to create a new user.

3. On the Register page, enter a user name and password, and then click Register.

4. Then, the application registers a new account, which is authenticated, and then automatically navigate to the home page.

5. Press F12 in the browser to open DevelZ development? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> vcGVyIFRvb2xzw + drawing/fCzMmrvP3Nt7C0xaXS1L + drawing =" here write picture description "src =" http://www.bkjia.com/uploads/allimg/160227/041P64091-13.png "title = "\ "/>

6. Add api/trivia to the URL in the browser address bar. You will detect the Response Details of Get actions from TriviaController.

Note: Once the download is complete, you will be prompted to perform operations on the downloaded file. Keep this dialog box to view the response content in the Developers Tool window.
7 now you can detect the response body. Click Details, and then click Response body. You can find that the downloaded data is an object corresponding to the TriviaQuestion class options (which is a list of TriviaOption objects), id, and title attributes.

8. Return to Visual Studio and press Shift + F5 to stop debugging.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.