I'm using Entity Framework
in a .NET Web API
(not Core) project with an Angular front end. Currently, the only examples of patch implementation I can find is for ASP.Net Core products - so I'd firstly like confirm if patch
is even possible in plain ol' ASP.Net Web API
(not Core).
I'd like to implement patch
in some of my controllers, but by default, the Entity controller does not seem to come with code for a patch operation. Instead it comes with GET
, PUT
, POST
and DELETE
. What code is needed in my Entity controller so that patch requests are valid? Is there a way to specify this when adding a new Entity controller, or must it always be entered in manually?
My controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using api.Models;
using api.Models.my_model;
using System.Net.Mail;
using System.Configuration;
namespace api.Controllers.my_model
{
public class myController : ApiController
{
private myCodeFirst db = new myCodeFirst();
// GET: api/my
public IQueryable<myTable> GetmyTable()
{
return db.myTable;
}
// GET: api/my/5
[ResponseType(typeof(myTable))]
public IHttpActionResult GetmyTable(int id)
{
myTable myTable = db.myTable.Find(id);
if (myTable == null)
{
return NotFound();
}
return Ok(myTable);
}
// PUT: api/my/5
[ResponseType(typeof(void))]
public IHttpActionResult PutmyTable(int id, myTable myTable)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != myTable.ID)
{
return BadRequest();
}
db.Entry(myTable).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!myTableExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/my
[ResponseType(typeof(myTable))]
public IHttpActionResult PostmyTable(myTable myTable)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.myTable.Add(myTable);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = myTable.ID }, myTable);
}
// DELETE: api/my/5
[ResponseType(typeof(myTable))]
public IHttpActionResult DeletemyTable(int id)
{
myTable myTable = db.myTable.Find(id);
if (myTable == null)
{
return NotFound();
}
db.myTable.Remove(myTable);
db.SaveChanges();
return Ok(myTable);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool myTableExists(int id)
{
return db.myTable.Count(e => e.ID == id) > 0;
}
}
}