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

查看:18
本文介绍了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天全站免登陆