我是一位能够提供翻译的助手。下面是需要翻译的内容:
如果有必要的话,BaseController自然地从ApiController派生而来。以下是需要的代码:
当我尝试使用$.getJSON调用我的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的工作方式,我还有很多不太清楚的地方...