JamTay317 JamTay317 - 20 days ago 9
ASP.NET (C#) Question

DELETE verb working in Postman but not with ajax

I have spent several hours researching this and just cannot figure it out.

first I' show you what i have

js:

function deleteContact(id) {
let url = baseUrl + "Contact/" + id;

var data = {
id : id
}

$.support.cors = true;
$.ajax({
url: url,
type: 'DELETE',
dataType: 'json',
data:data
});
}


I have a Contact Controller:

public class ContactController : SimpleController<Contact>
{
public ContactController (IRepository<Contact> repository) : base(repository)
{
}
}


and the SimpleController:

public abstract class SimpleController<T> : BaseController
where T : class, IEntity, new()
{
private readonly IRepository<T> _repository;

protected SimpleController (IRepository<T> repository)
{
_repository = repository;
}

[HttpGet]
public virtual IEnumerable<T> Get ()
{
var list = _repository.FindAll().ToList();
return list;
}

[HttpGet]
public virtual T Get (Guid id)
{
var entity = _repository.Find(id);
if ( entity == null )
throw new HttpResponseException(HttpStatusCode.NotFound);
return entity;
}

[HttpPost]
public virtual HttpResponseMessage Post (T entity)
{

if ( entity.Id != Guid.Empty )
throw new HttpResponseException(HttpStatusCode.BadRequest);

_repository.Add(entity);
_repository.Save();
var response = Request.CreateResponse<T>(HttpStatusCode.Created, entity);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = entity.Id }));
return response;
}

[HttpPatch]
public virtual T Patch (T entity)
{
var matchingItem = _repository.Find(entity.Id);
if ( matchingItem == null )
throw new HttpResponseException(HttpStatusCode.NotFound);
_repository.Update(entity);
_repository.Save();
return entity;
}

[HttpDelete]
public virtual void Delete (Guid id)
{
var matchingItem = _repository.Find(id);
if ( matchingItem == null )
throw new HttpResponseException(HttpStatusCode.NotFound);
_repository.Delete(id);
_repository.Save();
}
}


I will say that i'n postman this works it deletes the item but it doesnt using the ajax.

I have tried many things but still keep getting a 405
with a response that looks like this

{
"name": "Microsoft.ApplicationInsights.Dev.Request",
"time": "2016-11-13T12:41:02.0356067Z",
"tags": {
"ai.device.roleInstance": "James-Desktop.JAILAFILES.com",
"ai.operation.name": "OPTIONS Contact [id]",
"ai.operation.id": "9UbG1l7oEJA=",
"ai.internal.sdkVersion": "web: 2.1.0.363"
},
"data": {
"baseType": "RequestData",
"baseData": {
"ver": 2,
"id": "9UbG1l7oEJA=",
"name": "OPTIONS Contact [id]",
"startTime": "2016-11-13T07:41:02.0356067-05:00",
"duration": "00:00:02.4510180",
"success": false,
"responseCode": "405",
"url": "http://localhost:52136/api/Contact/96d53daa-deca-4dbd-8c6d-2a236387d258",
"httpMethod": "OPTIONS",
"properties": {
"DeveloperMode": "true"
}
}
}
}


I should also add that it never reaches the method called Delete but it does hit the simple controller constructor.

Update:

public Repository()
{
_context = new AlltechContext();
}

public virtual T Add(T entity)
{
if (entity.Id == Guid.Empty)
entity.Id = Guid.NewGuid();
return _context.Set<T>().Add(entity);
}

public virtual void Delete(Guid id)
{
var entity = _context.Set<T>().FirstOrDefault(x => x.Id == id);
_context.Set<T>().Remove(entity);
}

public virtual T Find(Guid id)
{
return _context.Set<T>().FirstOrDefault(x => x.Id == id);
}

public int Save()
{
try
{
return _context.SaveChanges();
}
catch (DbEntityValidationException ex)
{
var message = ex.EntityValidationErrors.Select(x=>x.ValidationErrors);
throw new ArgumentException(message.ToString());
}
}

public virtual IEnumerable<T> FindAll ()
{
return _context.Set<T>();
}

public virtual T Update (T entity)
{
var actualEntity = _context.Set<T>().FirstOrDefault(x => x.Id == entity.Id);
DuplicateItem(actualEntity, entity);
_context.Set<T>().Attach(actualEntity);
_context.Entry(actualEntity).State = EntityState.Modified;
return entity;
}

Answer

check if these lines are there in your Webconfig.cs under App_Start

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();////////////////////////////

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

If that line is not available goto package manager console use this command

Install-Package Microsoft.AspNet.WebApi.Cors

And then you might have that line might be commmented, if so un comment it.

add this line to your controller class

[EnableCors(origins: "http://localhost:55249",headers: "*", methods: "*")]

dont forget to include the namespace

using System.Web.Http.Cors;
Comments