Development environment
VS2012,. NET 4.5
Create a project
vs2012-> file-> New-> project, select asp.net MVC 4Web application
Select the Web API project and use the Razor engine
Directory structure
In App_start, RouteConfig.cs files Configure the routing rules for MVC, WebApiConfig.cs configure WEBAPI routing rules
Write a controller in the Controllers folder, you can write an MVC controller, and you can write a Webapi control, inheriting classes that are different. WEB API Routing
Config. Routes.maphttproute (
name: "Defaultapi",
routetemplate: "Api/{controller}/{id}",
defaults:new {id = Routeparameter.optional}
);
The route determines the format of the URL. The URL format for the default route is HTTP://LOCALHOST/API/STUDENT/1, which means accessing the Student controller and passing the ID
=1
6. Access rules
Get method: Query, no negative to do, no matter how many times the execution will not change the state of the system
Put method: Modify, perform one or more times, the change of System state is the same
Post method: New
Delete method: Deletes, executes one or more times, changes the system state is the same
Access by get means that all the action starts with a and matches the corresponding argument, and if two methods are found, an error is made. So the action at the start of get must have a different parameter.
Put, Post, delete is the same
Example:
Get api/values public
ienumerable<string> get ()
{return
new string[] {"value1", "value2"};
}
//Get API/VALUES/5 public
string get (int id)
{return
"value";
}
You can access a Get method without parameters in the following ways:
Get http://localhost/Student/
You can also change access by adding attributes to the action.
Get API/VALUES/5
[httpput] public
string get (int id)
{return
' value ';
}
After adding httpput, you can access the action by using the action name only through the Put method
You can add routing rules to the WebApiConfi.cs file
Config. Routes.maphttproute (
name: "Defaultapi",
routetemplate: "Api/{controller}/{action}/{id}",
defaults: New {id = routeparameter.optional}
);
This allows you to access the action by the action name
If the action does not start with GET, post, and so on, you must add an attribute such as HttpGet. Otherwise, there will be an access error.