【问题标题】:Attribute to apply to non-OK responses应用于非 OK 响应的属性
【发布时间】:2017-08-07 16:09:05
【问题描述】:

如果我有控制器 GET 方法,例如:

    [HttpGet]
    [Route("accountrecv({accountid})/promisepay", Name = "GetPromisePay")]
    public HttpResponseMessage GetPromisePay(int accountid)
    {
        var query = Request.RequestUri.Query;
        var uri = new Uri(Client.Instance.BaseAddress.ToString() + accountid + "/promisepay" + query);
        var request = new HttpRequestMessage { RequestUri = uri, Method = HttpMethod.Get };
        var response = Client.Instance.SendAsync(request);
        return response.Result;
    }

如何在HttpStatusCode 不正确的所有响应上施加行为?

我想我会在方法级别创建一个属性,例如:

[NonOKResponse]
[HttpGet]
[Route.......]
public HttpResponseeMessage GetPromisePay(int accountid)
{
//my code
return response.Result //but force it here to return 404 for EVERY response other than 200
}

我如何定义一个可以在所有 GET 上使用的属性,以根据某些标准强制执行特定响应?

【问题讨论】:

  • 为什么不在返回结果前检查response的状态码?
  • 因为我有数百个控制器,可能还有数千个方法,我需要应用这种行为
  • 实现IResultFilter 的ActionFilter 可以在这里工作吗?

标签: c# asp.net .net asp.net-web-api2 visual-studio-2017


【解决方案1】:

我相信this article 会回答您的问题。您可以使用ExceptionFilterAttribute 来处理和管理异常。例如:

public class GeneralExceptionFilterAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext context)
    {
        context.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
    }
}

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 2017-11-02
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多