ASP.NET核心是否可以仅在开发模式下在控制器中配置动作? [英] ASP.NET core it's possible to configure an action in controller only in development mode?

查看:50
本文介绍了ASP.NET核心是否可以仅在开发模式下在控制器中配置动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET核心Web应用程序中,我想要一个仅在开发模式下运行的操作.在生产模式下,可能会出现404错误就足够了.可以这样做吗?

In my ASP.NET core web application, I want to have an action that runs only in development mode. In production mode, maybe a 404 error will be good enough. Is it possible to do that?

推荐答案

这可以通过将IHostingEnvironment注入到控制器中并在动作本身内部使用其IsDevelopment()方法来实现.这是一个完整的示例,在开发环境以外的任何环境下运行时,都会返回404:

This can be achieved by injecting IHostingEnvironment into your controller and using its IsDevelopment() method inside of the action itself. Here's a complete example that returns a 404 when running in anything other than the Development environment:

public class SomeController : Controller
{
    private readonly IHostingEnvironment hostingEnvironment;

    public SomeController(IHostingEnvironment hostingEnvironment)
    {
        this.hostingEnvironment = hostingEnvironment;
    }

    public IActionResult SomeAction()
    {
        if (!hostingEnvironment.IsDevelopment())
            return NotFound();

        // Otherwise, return something else for Development.
    }
}

对于ASP.NET Core 3.0+,使用IWebHostEnvironmentIHostEnvironment代替IHostingEnvironment.

For ASP.NET Core 3.0+, use IWebHostEnvironment or IHostEnvironment in place of IHostingEnvironment.

如果您想更广泛地应用此功能,或者只是想分离出问题,Daboul在

If you want to apply this more globally or perhaps you just want to separate out the concerns, Daboul explains how to do so with an action filter in this answer.

这篇关于ASP.NET核心是否可以仅在开发模式下在控制器中配置动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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