This article attempts to increase the use of the ASP. NET Web API on an existing ASP. NET MVC 4 project.
New project, select "ASP. NET MVC 4 Web application".
Select the "Basic" project template.
Under the Controllers folder, add an empty API controller called "TestController".
The following assemblies are more in the reference folder:
System.Web.Http
System.Web.Http.WebHost
System.Net.Http
System.Net.Http.Formatting
......
There are more webapiconfig static classes in the App_start folder:
Public Static class Webapiconfig
{
Public Static void Register (httpconfiguration config)
{
Config. Routes.maphttproute (
Name: "defaultapi",
Routetemplate: "api/{controller}/{id}",
New {id = routeparameter.optional}
);
}
}
Modify the TestController content as follows:
Public class Testcontroller:apicontroller
{
Public ienumerable<string> Get ()
{
return New string [] {"value1", "value2"};
}
Public string Get (int ID)
{
return "value";
}
}
In the browser, type: http://localhost:3928/api/test
In the browser, type: HTTP://LOCALHOST:3928/API/TEST/5
Under the Controllers folder, add an empty MVC controller called "HomeController".
Public class Homecontroller:controller
{
Public ActionResult Index ()
{
return View ();
}
Add the home/index.cshtml view, modified 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>
}
As you can see, by adding an empty API controller to controllers, the ASP and configuration files are added by default.
ASP. NET Web API Practice Series 06, increasing the use of ASP. Net. NET MVC 4