Asp.net mvc 4 是否可以从Web API构造函数返回响应?

Asp.net mvc 4 是否可以从Web API构造函数返回响应?,asp.net-mvc-4,asp.net-web-api,Asp.net Mvc 4,Asp.net Web Api,我有一个Web API ApicController基类,我想在构造函数中执行一些验证。这可能包括检查服务器上的当前负载。如果它很高,我想返回一个适当的HttpResponseMessage,指示请求者应该稍后再试 这样做可能吗?即使您正在做的事情听起来可能更适合修改方法。请注意,您可以抛出HttpResponseException,因为WebApi是Rest服务HttpResponseException是将异常抛出回客户端的推荐方法 var resp = new HttpResponseMes

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


这样做可能吗?

即使您正在做的事情听起来可能更适合修改方法。请注意,您可以抛出
HttpResponseException
,因为
WebApi
是Rest服务
HttpResponseException
是将异常抛出回客户端的推荐方法

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

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

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


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

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

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);
    }
}

您不能在构造函数中抛出HttpResponseException,这将始终导致500

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

public override Task ExecuteAsync(HttpControllerContext controllerContext,CancellationToken CancellationToken){
如果(!myAuthLogicCheck()){
//返回401未授权
var msg=newhttpresponsemessage(HttpStatusCode.Unauthorized){ReasonPhrase=“用户未登录”};
抛出新的HttpResponseException(msg);
}
返回base.ExecuteAsync(controllerContext,cancellationToken);
}

您最好在应用程序事件中执行类似操作。请参阅global.asax文件,可能使用
BeginRequest
事件。@mximitle是正确的。如果你确定这是你想要走的路,你应该继承ApicController并创建你自己的ApicController,你所有的控制器都从中继承。谢谢你的好主意。我已经在使用一些ActionFilterAttributes,所以我想我会走这条路。
config.MessageHandlers.Add(new MyHandler());
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);
}