我有這兩個微控制器:爲什麼兩個相同的REST請求中的一個工作而不是另一個?
[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,但是當我請求分支時,我得到一個響應HTTP 405 - 方法不允許。現在我知道我正在使用POST向Get
方法發出請求,但是很久以前我才知道它出於某種原因更安全,並且通常工作正常。
這裏的要點是,這種經過驗證的模式一直適用於我,並且適用於所有其他此類控制器和POST請求在整個應用程序中。什麼可以使"/api/Branch"
的請求失敗?
更新:我改變了操作方法的簽名看起來是這樣,現在工作得很好:
[HttpPost]
[Route("Get")]
public async Task<IEnumerable<Branch>> Fetch()
這是奇怪的,因爲POST請求直接合作,在Get
行動上的所有其他控制器,只要HttpPost
屬性存在。我的問題已經解決,但這個問題仍然是開放的,爲什麼。與Jinish的回答相反,路線前綴開頭的/
似乎沒有區別。一些控制器有它,有些沒有,並且它們都工作,除了BranchController
。
您錯過了'[Route]'屬性,所以實際發生的是它默認返回到基於約定的路由。 '[Route(「」)]'適用於這兩種行爲。 – Nkosi