【问题标题】:Is it possible to return a response from a Web API constructor?是否可以从 Web API 构造函数返回响应?
【发布时间】:2018-06-07 04:34:08
【问题描述】:

我有一个 Web API ApiController 基类,我想在构造函数中执行一些验证。这可能包括检查服务器上的当前负载。如果它很高,我想返回一个适当的 HttpResponseMessage 指示请求者应该稍后再试。

这样的事情可能吗?

【问题讨论】:

  • 你最好在应用程序事件中做这样的事情。查看 global.asax 文件,可能使用 BeginRequest 事件。
  • @mxmissile 是对的。如果你确定这是你想要的路径,你应该继承 ApiController 并创建你自己的 ApiController,你的所有控制器都继承自。

标签: asp.net-mvc-4 asp.net-web-api


【解决方案1】:

我还没有测试过,但这不是构造函数的用途。我不认为所有的管道都在那个时候设置好了。

您可以为此使用全局过滤器。 Here您有一个为授权设置全局过滤器的示例,您应该使用类似的逻辑,但为您的特定目的创建自己的过滤器。

全局过滤器会拦截您的所有请求并在控制器操作之前执行,因此是执行任务的好地方。

【讨论】:

  • 感谢所有好主意。我已经在使用一些 ActionFilterAttributes,所以我想我会走那条路。
【解决方案2】:

尽管您正在做的事情听起来可能会更好地修改方法。请注意,您可以抛出HttpResponseException,因为WebApi 是Rest Service,HttpResponseException 是向客户端抛出异常的推荐方式。

var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
   Content = new StringContent("No idea what happened "),
   ReasonPhrase = "Something was not Not Found"
}
throw new HttpResponseException(resp);

【讨论】:

    【解决方案3】:

    只要您使用的是 .NET 4.5,那么您最好创建一个自定义 MessageHandler。您需要扩展 DelegatingHandler 才能做到这一点。

    public class MyHandler : DelegatingHandler {
        protected override async Task<HttpResponseMessage> SendAsync(
                HttpMessageRequest request, CancellationToken cancellationToken) {
            // Access the request object, and do your checking in here for things
            // that might cause you to want to return a status before getting to your 
            // Action method.
    
            // For example...
            return request.CreateResponse(HttpStatusCode.Forbidden);
        }
    }
    

    然后在您的WebApiConfig 中,只需添加以下代码即可使用新的处理程序:

    config.MessageHandlers.Add(new MyHandler());
    

    【讨论】:

      【解决方案4】:

      你不能在构造函数中抛出 HttpResponseException,那总是会导致 500。

      最简单的方法是重写 ExecuteAsync():

      public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) {
              if (!myAuthLogicCheck()) {
                  // Return 401 not authorized
                  var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "User not logged in" };
                  throw new HttpResponseException(msg);
              }
      
              return base.ExecuteAsync(controllerContext, cancellationToken);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-17
        • 2018-01-09
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多