Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

c# - ASP.NET core it's possible to configure an action in controller only in development mode?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.
    }
}

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...