УДАЛИТЬ localhost / API не найден, MVC - PullRequest
0 голосов
/ 30 апреля 2018

Я сделал веб-API из Entity Framework, а затем попытался сделать вызов DELETE, чтобы я мог удалить материал из моего jquery, доступного для данных, через AJAX. Я получаю сообщение об ошибке, что DELETE localhost / api не найден. Вот мой код.

    @section scripts{
<script>
$(document).ready( function () {
    var table = $('#myTable').DataTable();
    $("#myTable .js-delete").on("click", function () {
        var button = $(this);
        //bootbox.confirm("Do you want to delete this movie?", function (result) {
            //if (result) {
                $.ajax({
                    url: "/api/FriendApi/" + button.attr("data-friend-id"),
                    method: "DELETE",
                    success: function () {
                        table.row(button.parents("tr")).remove().draw();
                    }
                });
            //}
        //});
    })
} );
</script>
    }

Это мой веб-интерфейс

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebApplication2
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

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

ApiController

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 WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class FriendApiController : ApiController
    {
        private FriendContext db = new FriendContext();

        // GET: api/FriendApi
        public IQueryable<FriendModel> Getfriends()
        {
            return db.friends;
        }

        // GET: api/FriendApi/5
        [ResponseType(typeof(FriendModel))]
        public IHttpActionResult GetFriendModel(int id)
        {
            FriendModel friendModel = db.friends.Find(id);
            if (friendModel == null)
            {
                return NotFound();
            }

            return Ok(friendModel);
        }

        // PUT: api/FriendApi/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutFriendModel(int id, FriendModel friendModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != friendModel.Id)
            {
                return BadRequest();
            }

            db.Entry(friendModel).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FriendModelExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/FriendApi
        [ResponseType(typeof(FriendModel))]
        public IHttpActionResult PostFriendModel(FriendModel friendModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.friends.Add(friendModel);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = friendModel.Id }, friendModel);
        }

        // DELETE: api/FriendApi/5
        [ResponseType(typeof(FriendModel))]
        [Route("FriendModel/{id}")]
        public IHttpActionResult DeleteFriendModel(int id)
        {
            FriendModel friendModel = db.friends.Find(id);
            if (friendModel == null)
            {
                return NotFound();
            }

            db.friends.Remove(friendModel);
            db.SaveChanges();

            return Ok(friendModel);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool FriendModelExists(int id)
        {
            return db.friends.Count(e => e.Id == id) > 0;
        }
    }
}

По сути, это мой WebApi и Api, которые я сделал сам (в данном случае я использовал Api Framework для Entity). Я написал тот же код, что и неделю назад, и он работал, но теперь он не работает. Понятия не имею, почему.

1 Ответ

0 голосов
/ 30 апреля 2018

Ваш код C # имеет:

[Route("FriendModel/{id}")]

Но ваш скрипт запрашивает:

DELETE /api/FriendApi/{id}

Найди разницу!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...