當我嘗試使用$ .getJSON調用Web API控制器方法時,我遇到了令人沮喪的問題:它始終以顯示的以下消息結束控制檯:「無法加載資源:服務器與405狀態響應(不允許的方法)」Web API上的405錯誤(方法不允許)獲取
這裏是我的控制器:
using MyProject.Domain;
using MyProject.WebApp.Session;
using System;
using System.Linq;
using System.Web.Mvc;
namespace MyProject.WebApp.ApiControllers.Favorites
{
public class FavoriteArticlesController : BaseController<FavoriteArticle, Guid>
{
[HttpGet]
public object SetFavorite(Guid articleId, bool isFavorite)
{
try
{
if (isFavorite)
{
var favorite = new FavoriteArticle
{
UserId = UserInfo.GetUserId(),
ArticleId = articleId
};
_repo.Upsert(favorite);
}
else
{
var favorite = _repo.GetAll()
.First(fa => fa.ArticleId.CompareTo(articleId) == 0);
_repo.Delete(favorite.Id);
}
_repo.Commit();
return new { Success = true, Error = (string)null };
}
catch (Exception ex)
{
return new { Success = false, Error = ex.Message };
}
}
}
}
在與其相關的任何情況下,BaseController自然派生來自ApiController。下面是如果需要的代碼:
using MyProject.Data.Repository;
using MyProject.Data.Services;
using MyProject.Domain;
using System.Web.Http;
namespace MyProject.WebApp.ApiControllers
{
public class BaseController<TEntity, TKey> : ApiController
where TEntity : class, IEntity<TKey>, new()
{
protected UnitOfWork _unitOfWork;
protected Repository<TEntity, TKey> _repo;
protected BaseController()
{
_unitOfWork = new UnitOfWork();
_repo = _unitOfWork.GetRepository<TEntity, TKey>();
}
}
}
而這裏的是撥打電話的功能之一:
$.fn.bindFavoriteArticle = function() {
this.click(function() {
var link = $(this);
$.getJSON('/api/FavoriteArticles/SetFavorite', { ajax: true, articleId: link.attr('data-target-id'), isFavorite: true }, function (response) {
if (response.Success === true) {
link.children('i').removeClass('fa-heart-o')
.addClass('fa-heart');
link.attr('data-toggle', 'unfavoriteArticle')
.unbind('click')
.bindUnfavoriteArticle();
} else {
// TODO : use bootstrap alert messages
alert(response.Error);
}
});
});
};
我看到在這裏和那裏的路由配置可能是問題的根源,所以這裏的RouteConfig.cs的內容:
using System.Web.Mvc;
using System.Web.Routing;
namespace MyProject.WebApp
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "ApiDefault",
url: "api/{controller}/{action}/{id}",
defaults: new { controller = "SubscriptionsController", action = "GetSelectList", id = UrlParameter.Optional }
);
}
}
}
想知道發生了什麼?我覺得我有很多關於Web API如何工作的想法...
嘗試將link.attr('data-target-id')添加到'/ api/FavoriteArticles/SetFavorite' –