如何强制我的控制器返回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的有用评论,我创建了自己的对象:
然而行为是一样的!该方法将超出范围,但客户端看不到任何内容。它只是超时了。
我的最新更新是:
[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);
}
行为再次相同。
答案 0 :(得分:1)
根据评论中的讨论,建议您查看响应管道,因为确定操作中的代码正在按预期处理/执行请求。问题是在管道出口导致客户超时的情况下遇到的问题。检查管道中的消息处理程序和中间件,这些消息处理程序和中间件可能导致响应根据管理器的处理方式阻塞其在管道上的阻塞。
请考虑以下内容,使用首选的Web API 2. *语法以及正确使用async / await。
[HttpGet]
[Route("account({accountid})/printgroup", Name = "Get")]
public async Task<IHttpActionResult> 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 = await Client.Instance.SendAsync(request);
if (clientResponse.StatusCode == System.Net.HttpStatusCode.NotFound)
return NotFound();
return ResponseMessage(clientResponse);
}
答案 1 :(得分:1)
添加此中间件后,问题已解决:
public class NotFoundMiddleware : OwinMiddleware
{
public NotFoundMiddleware(OwinMiddleware next) : base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
await Next.Invoke(context);
if (context.Response.StatusCode == (int)HttpStatusCode.NotFound
&& !context.Response.Headers.ContainsKey("X-ServiceFabric")
)
context.Response.Headers.Add("X-ServiceFabric", new[] { "ResourceNotFound" });
}
}