-1

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?

İsmail Kasap
  • 109
  • 1
  • 11

1 Answers1

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.

enter image description here

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
  • 1
    In 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