DELETE动词在Postman中工作,但没有使用ajax

时间:2016-11-13 12:56:38

标签: asp.net asp.net-web-api

我花了几个小时研究这个,但是无法理解。

首先我'告诉你我有什么

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
    });
}

我有一个Contact Controller:

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

和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();
    }
}

我会说我的邮递员可以删除该项,但它不使用ajax。

我尝试了很多东西,但仍然保持着405 回复看起来像这样

    {
  "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"
      }
    }
  }
}

我还应该补充一点,它永远不会到达名为Delete的方法,但它确实击中了简单的控制器构造函数。

更新

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;
    }

1 个答案:

答案 0 :(得分:2)

检查App_Start

下的Webconfig.cs中是否存在这些行
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 }
            );
        }
    }
}

如果该行不可用,请转到包管理器控制台 使用此命令

Install-Package Microsoft.AspNet.WebApi.Cors

然后你可能会对该行进行修改,如果没有评论它。

将此行添加到控制器类

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

不要忘记包含命名空间

using System.Web.Http.Cors;