How to use ASP. NET Web Api to build a REST-style service? series of tutorials [3]-Introduction to Web APIs

Source: Internet
Author: User

Series Navigation Address http://www.cnblogs.com/fzrain/p/3490137.html

After the introduction in the first two sections, we have set up the data access layer. From this chapter, we will start with the Web Api section. Before the formal start, let's review the application scenarios of Web APIs: Web APIs can be used in combination with MVC and WebForm, or as a separate Web service. Before formally discussing the Web Api configuration and how to construct a URI to consume resources, we must understand the relationship between the Http method and the resources we will access. For a simple example, we use the model "Course" as the resource we access. The following lists the http methods used to access this resource:

Action HTTP Verb Relative URI
Obtain all course information GET /Api/courses
Obtain a single course by Id GET /Api/courses/Id
Add a course POST /Api/coursesNew course is sent in POST body
Update a course PUT or PATCH /Api/courses/IdUpdated course is sent in POST body
Delete A Course DELETE /Api/courses/Id

 

Right-click solution> Add new project

After creating a project, we can see the "WebApiConfig" Class in the App_Start folder. This class is used to configure the routing information. the Application_Start () method of asax is called. We will configure multiple routes in this class later.

Configure the first route:

 {controller=, id =

Analyze the above Code: we have created a Courses routing rule, which will match the URI of "api/courses/{id, this template defines two default values (api, courses) and an optional value (id ). For/Api/coursesOr/Api/courses/5"URI will be matched by our routing template, and"/Api/courses"URI will also be matched, because Id is optional.

The Controller in the Web Api is used to process the Http request from the client (similar to the Controller in MVC). First, create the Controller, right-click the Controller folder, and choose create item> Controller.

The following window is displayed:

First, we create the first two methods (GetAllCourses, GetCourseById) listed in the preceding table)

The method selection is intelligent. If we create two methods Get () and GetCourse (int id), let's assume that we send a GET request and the URI is"/Api/courses/5", Then the" GetCourse (int id) "method will be selected for execution, because the method starts with Get and the URI contains the Id value. This method also applies to other Http methods (put, delete, post). The following code is used:

  List<Course>=  LearningRepository( Course GetCourse(=  LearningRepository(

When we create a Get request and the URI is"Http: // localhost :{Your_port}/Api/courses", The Get () method will be selected for calling. The following is the corresponding code:

"Id": 1"Name": "History Teaching Methods 1""Duration": 3"Description": "The course will talk in depth about: History Teaching Methods 1""CourseTutor""Courses""Id": 1"Email": "Ahmad.Joudeh@outlook.com""UserName": "AhmadJoudeh""Password": "SWDQNPSE""FirstName": "Ahmad""LastName": "Joudeh""Gender": 0"CourseSubject""Courses""Id": 1"Name": "History""Enrollments""Id": 2"Name": "History Teaching Methods 2""Duration": 3"Description": "The course will talk in depth about: History Teaching Methods 2""CourseTutor""Courses""Id": 1"Email": "Ahmad.Joudeh@outlook.com""UserName": "AhmadJoudeh""Password": "SWDQNPSE""FirstName": "Ahmad""LastName": "Joudeh""Gender": 0"CourseSubject""Courses""Id": 1"Name": "History""Enrollments"

If you send a Get request and the URI is"Http: // localhost :{Your_port}/Api/courses/5". Then, GetCourse (int id) will be selected for invocation. However, it is a pity that an exception will occur after this method is called. The exception information is simply "circular dependency occurs when the object is serialized ", in other words, it is a circular reference between objects (Course> Enrollment> etc ...)

So far, we have made Web APIs run, but there are still many shortcomings:

Circular dependency occurs when an object is returned, which can be solved through the model factory mode.

We return all fields of the domain model to the client, but some sensitive information should not be returned (for example, the password field). Solution: model factory Mode

Every resource returned to the client should contain a URI for the client to query. The solution is still in the model factory mode.

For a single resource, we should return the corresponding status code (for example, success 200, resource not found 404, etc.). Solution: HttpResponseMessage object

In each method, we instantiate a repository object that contains some expensive operations (such as database connections). Solution: dependency injection mode

The format of the returned Json object is "Pascal" (for example, "FirstName"). However, our Api may be consumed by clients with Javascript, JS developers may be more suitable for data in the "camper" style (such as "firstName. Solution: configure the Json format.

OK. In the next chapter, we will focus on solving the above problems.

This chapter code: http://yun.baidu.com/share/link? Required id = 2010367762 & uk = 17559114 & third = 0

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.