【问题标题】:Why does one of two identical REST requests work and not the other?为什么两个相同的 REST 请求之一有效,而另一个无效?
【发布时间】:2016-11-22 12:02:40
【问题描述】:

我有这两个小控制器:

[AllowAnonymous]
[RoutePrefix("api/Org")]
public class OrgController : BaseController
{
    [HttpPost]
    public async Task<IEnumerable<Organization>> Get()
    {
        Db.Configuration.LazyLoadingEnabled = false;
        return await Db.Organizations.ToListAsync();
    }
}

[AllowAnonymous]
[RoutePrefix("/api/Branch")]
public class BranchController : BaseController
{
    [HttpPost]
    public async Task<IEnumerable<Branch>> Get()
    {

        Db.Configuration.LazyLoadingEnabled = false;
        return await Db.Branches.ToListAsync();
    }
}

我分别这样称呼它们,使用System.Net.Http.HttpClient

HttpResponseMessage response = await Client.PostAsync("/api/Org", null, cancellation);

HttpResponseMessage response = await Client.PostAsync("/api/Branch", null, cancellation);

当我请求 Orgs 时,我有一个返回 4 个 Orgs 的成功请求,但是当我请求 Branches 时,我得到一个响应 HTTP 405 - Method not allowed。现在我知道我正在使用 POST 向 Get 方法发出请求,但很久以前我了解到它出于某种原因更安全,而且它通常可以正常工作。

这里的要点是,这种经过验证的模式一直对我有效,并且适用于整个应用程序中的所有其他此类控制器和 POST 请求。是什么导致"/api/Branch" 的请求失败?

更新:我将操作方法​​签名更改为如下所示,现在可以正常工作:

[HttpPost]
[Route("Get")]
public async Task<IEnumerable<Branch>> Fetch()

这很奇怪,因为只要存在HttpPost 属性,POST 请求就直接作用于所有其他控制器上的Get 操作。我的问题得到了解决,但这个问题仍然悬而未决。与 Jinish 的回答相反,路由前缀开头的 / 似乎没有什么区别。有些控制器有,有些没有,除了BranchController 之外,它们都可以工作。

【问题讨论】:

  • 您缺少[Route] 属性,所以实际发生的是它默认返回到基于约定的路由。 [Route("")] 对这两种操作都有效。

标签: asp.net-web-api https asp.net-web-api2 dotnet-httpclient


【解决方案1】:

我不相信您的 [RoutePrefix] 可以以“/”开头 应该是 [RoutePrefix("api/Branch")]

【讨论】:

  • 尝试删除/,我仍然得到完全相同的行为,但是,当我更改操作名称并将其别名为Get 时,一切开始正常。请参阅我上面的编辑。
【解决方案2】:

我使用的是System.Web.Mvc.AllowAnonymousAttribute 而不是System.Web.Http.AllowAnonymousAttribute。使用现代便利,当我添加属性时,我被提示(我认为是 ReSharper,但可能是 VS 本身)为它导入一个命名空间。匆忙中我没有注意到它们有两个名称空间作为选项,我选择了错误的一个。更正如下:

using System.Collections.Generic;
using System.Data.Entity;
using System.Threading.Tasks;
using System.Web.Http;
//using System.Web.Mvc;

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 2023-03-21
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多