ASP. NET Web API practice series 06, added the use of ASP. net web api, mvcasp.net
This article attempts to add ASP. NET Web APIs to the existing ASP. net mvc 4 Project.
Create a project and select "ASP. net mvc 4 Web application ".
Select the "Basic" Project template.
Add an empty API controller named "TestController" to the Controllers folder.
The following assembly is added to the referenced Folder:
System. Web. Http
System. Web. Http. WebHost
System. Net. Http
System. Net. Http. Formatting
......
WebApiConfig static classes are added to the App_Start Folder:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Modify the content of TestController as follows:
public class TestController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] {"value1","value2"};
}
public string Get(int id)
{
return "value";
}
}
Enter http: // localhost: 3928/api/test in the browser
Enter: http: // localhost: 3928/api/test/5 in the browser
Add an empty MVC controller named "HomeController" to the Controllers folder.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
Add the Home/Index. cshtml view and modify it as follows:
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section scripts
{
<script type="text/javascript">
$.get("http://localhost:3928/api/test", function (data) {
alert(data);
});
</script>
}
It can be seen that by adding an empty API controller to Controllers, ASP. NET Web API related components and configuration files are added by default.