ASP.NET Web API for .NET Framework 4 in Visual Studio 2015
This is a pretty unique set of constraints I know – sometimes there are limitations outside your control as to which version of .NET you (or those who will be running your software) can use.
Note that the most recent version of Web API that works with .NET Framework 4.0 is 4.0.30506.0 (The 5.x releases all require at least .NET 4.5)
- Open Visual Studio 2015
- Create a new project (Make sure you select .NET Framework 4 in the frameworks dropdown list)
- Open the Package Manger Console
- Enter
Install-Package -Id Microsoft.AspNet.WebApi -Version 4.0.30506 -DependencyVersion HighestMinor
Update-Package Newtonsoft.Json
- (Optional)
Install-Package -Id Microsoft.AspNet.WebApi.Tracing -Version 4.0.30506
- Add an
App_Start
folder - Inside this folder, add new class
WebApiConfig
- Add the following content to the WebApiConfig class:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new
{
id = RouteParameter.Optional
}
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}
- In the top-level of the project, add a Global.asax file
- Open the
Global.asax.cs
file and add the following method:
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
- Add a Controllers folder
- Inside the Controllers folder, add a new class (eg. ValuesController)
- Update the ValuesController class to look as follows:
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
Your project should look similar to this:
You can now build and run the web application and browse to /api/Values
and get a response from your controller (JSON or XML depending on your browser)
Categories: .NET