【发布时间】:2017-08-09 16:26:47
【问题描述】:
如何强制我的控制器返回 404?
[HttpGet]
[Route("account({accountid})/printgroup", Name = "Get")]
public HttpResponseMessage Get(int accountid)
{
var query = Request.RequestUri.Query;
var uri = new Uri(Client.Instance.BaseAddress.ToString().Replace("[accountid]", accountid.ToString()) + query);
var request = new HttpRequestMessage {RequestUri = uri, Method = HttpMethod.Get};
var clientResponse = Client.Instance.SendAsync(request).Result;
return clientResponse;
}
clientResponse 为 404 时,该方法不返回响应。它只是超时。
我做错了什么?如果客户端响应为 404,如何强制它返回 404?
编辑:
根据 macceturra 的有用 cmets,我创建了自己的对象:
但行为是一样的!该方法将超出范围,但客户端看不到任何内容。它只是超时。
我的最新更新是:
[HttpGet]
[Route("account({accountid})/bill({billingRunId})", Name = "GetInvoiceSummary")]
public async Task<IHttpActionResult> GetInvoiceSummary(int accountid, int billingRunId)
{
var query = Request.RequestUri.Query;
var uri = new Uri(Client.Instance.BaseAddress.ToString() + accountid + "/" + billingRunId + query);
var request = new HttpRequestMessage { RequestUri = uri, Method = HttpMethod.Get };
var response = await Client.Instance.SendAsync(request);
if (response.StatusCode == HttpStatusCode.NotFound)
return NotFound();
return ResponseMessage(response);
}
行为再次相同。
【问题讨论】:
-
您为什么要尝试返回另一个请求的
HttpResponse作为您自己的响应? -
您不会在任何地方抛出 404。 WebApi 并不关心 HttpResponseMessage 的属性是否为 = 404。它只是将对象序列化并将其返回给调用者。您应该检查响应,如果您的呼叫响应是 404,则抛出
new HttpNotFoundException()。我要补充一点,返回 HttpResonseMessage 而不是您想要/需要的实际对象似乎是个坏主意。此外,您正在通过不等待异步调用来阻塞线程。 -
@maccettura 为什么我需要等待电话?
-
在你这样做之前,你的代码不是异步的。
-
经验法则:如果您在
Task<T>上调用.Result,那么您做错了。
标签: c# asp.net .net asp.net-web-api2 visual-studio-2017