【发布时间】: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