是否可以从Web API构造函数返回响应? [英] Is it possible to return a response from a Web API constructor?

查看:85
本文介绍了是否可以从Web API构造函数返回响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Web API ApiController base class and I would like to perform some validations in the constructor. This might include checking the current load on the server. If it's high, I'd like to return an appropriate HttpResponseMessage indicating the requestor should try again later.

这样可能吗?

推荐答案

我尚未对其进行测试,但这不是构造函数的用途.我认为当时还没有设置好所有管道.

I Haven't tested it but that's not what the constructor is for. I don't think all plumbing is set at that time.

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

You could use global filters for this purpose. Here you have a sample that sets a global filter for authorization, you should use a similar logic but creating your own filter for your specific purposes.

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

A global filter would intercept all your requests and is executed before the controller actions so is a good place to perform your task.

这篇关于是否可以从Web API构造函数返回响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆