Developing HTTP interfaces with ASP.

Source: Internet
Author: User
Tags connectionstrings

Development tools

Visual Studio 2013

SQL Server R2

Preparatory work

Start Visual Studio 2013, create a new ASP. NET Web application named Simpleapi. Select the empty template and tick "Web API" without authentication and add unit tests.

Prepare to use SQL Server database to store data, so install the next Entity Framework framework, eliminating the hassle of writing cumbersome SQL statements. Open the Tools-"Package Manager Console" to install the following command.

Install-package EntityFramework

In the Web. config file, configure the database connection code, open the file, add a connection string within the configuration node, where the asterisk section is replaced by the SQL Server database name.

<connectionstrings><add name= "defaultconnection" connectionstring= "Data source=localhost;initial Catalog= ; Integrated Security=sspi; "Providername=" System.Data.SqlClient "/></connectionstrings>
Building a data Model

Create a new class file named Friend.cs in the models directory.

public class Friend {public    int ID {get; set;}    public string FirstName {get; set;}    public string LastName {get; set;}    public string Address {get; set;}    public string City {get; set;}    public string PostalCode {get; set;}    public string Country {get; set;}    public string Notes {get; set;}  }

Create a context class file for the database at the same time.

public class friendcontext:dbcontext{public    Friendcontext ()        : Base ("Name=defaultconnection")    {    }    Public dbset<friend> Friends {get; set;}    protected override void Onmodelcreating (Dbmodelbuilder modelBuilder)    {        ModelBuilder.Conventions.Remove <PluralizingTableNameConvention> ();    }}

Description

1. Name=defaultconnection is consistent with name in the database connection string in Web. config.

2. The function of onmodelcreating overload function is to make the name of the data table created in the singular format, that is, friend, not friends.

Then, in the package management console, enable migrations, generate the Migrations directory, and the Configuration.cs configuration file in the directory.

Enable-migrations

It is convenient to import the data model you just created into SQL Server by executing the following 2 commands in turn.

Add-migration Xxxupdate-database

where xxx can be filled in, VS will generate a file named 201508051223177_xxx.cs, 201508051223177 is the current time, the file contains up and down two methods. Now we go to SQL Server to refresh the view, we will find a data table called Friend is established.

The following simulation data is added under the seed method by adding some test data using the seed function in Configuration.cs.

var friend = new friend{    FirstName = "Three",    LastName = "Zhang",    Address = "Nanjingxilu", City    = "Shanghai",    country = "China ",    PostalCode =" 200041 ",    Notes =" www.zhaomu.com "};context. Friends.add (friend), friend = new friend{    FirstName = "Four",    LastName = "Li",    Address = "Three Li Tun", City    = "Beijing", C11/>country = "China",    PostalCode = "100600",    Notes = "www.sohu.com"};context. Friends.add (friend), friend = new friend{    FirstName = "Five",    LastName = "King",    Address = "Huacheng Avenue", City    = "Guang State ",    country =" China ",    PostalCode =" 510623 ",    Notes =" www.163.com "};context. Friends.add (friend);

After executing the Update-Database command, the data is successfully imported into the SQL Server data sheet.

Create a Controller

In the Controllers directory to add the controller, select "WEB API 2 Controller-NULL", we will manually write API program read, add, modify, delete the common interface. The controller file is named FriendController.cs.

Read the Get method and add the following code in FriendController.cs.

Private Friendcontext db = new Friendcontext ();p ublic ienumerable<friend> Get () {    return db. Friends.asenumerable ();}

After compiling, we access Http://localhost:61570/api/friend (61570 is the random port), if everything is OK, the following XML format data will appear, indicating that the data read successfully.

Convert to JSON format display

Now more popular JSON format API interface data, if we want to show the data in JSON format, we need to modify the WebApiConfig.cs file in the App_start directory, add the following code under the comments of//web API configuration and service:

Config. Formatters.remove (config. Formatters.xmlformatter); var jsonformatter = config. formatters.jsonformatter;jsonformatter.serializersettings.formatting = Newtonsoft.Json.Formatting.Indented; JsonFormatter.SerializerSettings.ContractResolver = new Camelcasepropertynamescontractresolver ();

Note: The first line is to remove the default XML format, so that the output data will be displayed in JSON format, the third line is to indent the output results display, the fourth line is to change the field name to CamelCase format, that is, PostalCode, such as the JSON unified format. Then we run again and we find the result is what we want.

In the second part we will continue to complete the operations of adding, modifying, and deleting data with ASP. NET WEB API technology, then we will use a very useful interface test tool rest client in the browser on the newly developed API interface to actually run.

Developing HTTP interfaces with ASP.

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.