I am developing a project with asp.net mvc architecture. I would like to add services with the asp.net web api. How can I incorporate it into the exist project?
Asked
Active
Viewed 1,883 times
-1
-
What do you mean "How can I incorporate"? – mason Sep 26 '17 at 19:26
-
Do you use any IoC container in existing MVC application? – Win Sep 26 '17 at 19:28
-
I would like to add web API to exist project. But I do not know what files I should add and what settings I should make... – İsmail Kasap Sep 26 '17 at 19:29
-
No i have never used IoC. – İsmail Kasap Sep 26 '17 at 19:32
-
Duplicate of [How to add Web API to an existing ASP.NET MVC 4 Web Application project?](https://stackoverflow.com/questions/11990036/how-to-add-web-api-to-an-existing-asp-net-mvc-4-web-application-project) – Igor Sep 26 '17 at 19:32
1 Answers
1
For ASP.NET MVC 4, the easiest way is to create a new Web API project in Visual Studio 2015, and see how the project is set up.
Basically, you just need to add the following packages as of today, and the following codes -
Packages
Install-Package Microsoft.AspNet.WebApi
Install-Package Microsoft.AspNet.WebApi.Client
Install-Package Microsoft.AspNet.WebApi.Core
Install-Package Microsoft.AspNet.WebApi.WebHost
Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
...
GlobalConfiguration.Configure(WebApiConfig.Register);
...
}
}
App_Start/WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Testing
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}

Win
- 61,100
- 13
- 102
- 181
-
1In addition to this, it is important to place GlobalConfiguration.Configure(WebApiConfig.Register); before RouteConfig.RegisterRoutes(RouteTable.Routes);, otherwise while calling api, 404 will be returned – Vahid Farahmandian Jul 08 '19 at 09:39