gpt4 book ai didi

c# - Web API get 上的 405 错误(方法不允许)

转载 作者:行者123 更新时间:2023-11-30 23:12:32 27 4
gpt4 key购买 nike

当我尝试使用 $.getJSON 调用我的 Web API Controller 方法时,我遇到了一个令人沮丧的问题:它总是以控制台中显示以下消息结束:“无法加载资源:服务器响应状态为 405(方法不允许)”

这是我的 Controller :

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 的工作原理,我觉得我遗漏了很多东西......

最佳答案

如其他答案之一所述,代码配置了错误的路由。对于 web api 配置 WebApiConfig

public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Web API routes

//Enable Attribute routing is they are being used.
config.MapHttpAttributeRoutes();

//Convention based routes.

//Matches GET /api/FavoriteArticles/SetFavorite
config.Routes.MapHttpRoute(
name: "DefaultActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

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

确保它在 MVC 路由之前配置。

protected void Application_Start() {
// Pass a delegate to the Configure method.
GlobalConfiguration.Configure(WebApiConfig.Register);
//...other configurations
}

一些关于重构 Controller 以使其更安静的建议。尝试从操作中返回 IHttpActionResult。简化框架并让您更好地控制响应的返回方式。

[RoutePrefix("api/favoritearticles"]
public class FavoriteArticlesController : BaseController<FavoriteArticle, Guid> {


[HttpPost]
[Route("{articleId:guid}")] //Matches POST api/favoritearticles/{articleId:guid}
public IHttpActionResult SetFavorite(Guid articleId) {
var favorite = new FavoriteArticle
{
UserId = UserInfo.GetUserId(),
ArticleId = articleId
};
_repo.Upsert(favorite);
_repo.Commit();
return Ok(new { Success = true, Error = (string)null });
}

[HttpDelete]
[Route("{articleId:guid}")] //Matches DELETE api/favoritearticles/{articleId:guid}
public IHttpActionResult RemoveFavorite(Guid articleId) {
var favorite = _repo.GetAll()
.First(fa => fa.ArticleId == articleId);

if(favorite == null) return NotFound();

_repo.Delete(favorite.Id);
_repo.Commit();
return Ok(new { Success = true, Error = (string)null });
}
}

Controller 应该尽可能精简,因此即使是上述内容也应该通过向 Controller 注入(inject)服务来进一步精简。

错误处理是一个横切关注点,也应该通过框架的扩展点提取和处理。

关于c# - Web API get 上的 405 错误(方法不允许),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44051992/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com