Skip to content

Instantly share code, notes, and snippets.

@Hereigo
Last active July 28, 2017 09:30
Show Gist options
  • Save Hereigo/38bb2bb2d248352db02b4d1aa7d06c67 to your computer and use it in GitHub Desktop.
Save Hereigo/38bb2bb2d248352db02b4d1aa7d06c67 to your computer and use it in GitHub Desktop.
PS - Web API with .NET Framework 4.0 (with ELMAH)
// 1. Install-Package -Id Microsoft.AspNet.WebApi -Version 4.0.30506 -DependencyVersion HighestMinor
// 2. Update-Package Newtonsoft.Json
// 3. Install-Package -Id Microsoft.AspNet.WebApi.Tracing -Version 4.0.30506 // (it is Optional)
// For Elmah : Install-Package elmah -Version 1.2.2
// 4. Add - App_Start/WebApiConfig.cs
public class WebApiConfig
{
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();
// For ELMAH only :
config.Filters.Add(new UnhandledExceptionFilter());
}
// 5. Add a Global.asax file and open the Global.asax.cs:
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
// For ELMAH only :
public class UnhandledExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(context.Exception));
}
}
// 6. Add - Controllers/ValuesController.cs:
public class ValuesController : ApiController // : ApiController !!!
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value-" + id;
}
// 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)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment