我有一个Web API ApiController基类,我想在构造函数中执行一些验证。这可能包括检查服务器上的当前负载。如果它很高,我想返回一个适当的HttpResponseMessage,指示请求者应该稍后重试。
这样的事情有可能发生吗?
发布于 2014-08-14 01:58:58
我还没测试过,但这不是构造函数的目的。我不认为所有的管道都在那个时候准备好了。
为此,您可以使用全局筛选器。Here您有一个为授权设置全局筛选器的示例,您应该使用类似的逻辑,但要为您的特定目的创建自己的筛选器。
全局过滤器将拦截所有请求,并在控制器操作之前执行,因此是执行任务的好地方。
发布于 2014-08-14 01:57:55
即使你正在做的事情听起来像是修改方法可能会更好。请注意,您可以抛出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);
发布于 2014-08-14 01:59:54
只要你使用的是.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());
https://stackoverflow.com/questions/25292907
复制相似问题