C
C#

help

❔ ASP.NET Core how to let a controller be mapped only in development mode

AAnton11/12/2022
This is pretty easy to do with minimal API's, you just do a check and map only if it succeeds:
app.UseEndpoints(endpoints =>
{
if (app.Environment.IsDevelopment())
{
endpoints.Map("whatever", () => "blah");
}
});
app.UseEndpoints(endpoints =>
{
if (app.Environment.IsDevelopment())
{
endpoints.Map("whatever", () => "blah");
}
});
However, as I've noticed, minimal endpoints have somewhat different semantics than normal controller actions. For example, they can't match catch all routes. So the following won't work:
endpoints.Map("/{**catchAll}", async (HttpContext http, string catchAll) => "whatever");
endpoints.Map("/{**catchAll}", async (HttpContext http, string catchAll) => "whatever");
With controllers I think it does work. Minimal API's specificity is quite weird too. They'd match a request even having a less specific route than some of the controllers. It's as though they're treated completely separately, idk. To be clear, I don't want to make a filter and then check if it's development mode in the filter of the controller, or whatever. I don't want it to be mapped at all if it's not development.
Pplam11/12/2022
As far as I am concerned, it is actually possible via using IHostEnvironment inside your controller class, and basically checking for the same thing:
if (_hostEnvironment.IsDevelopment()) {..}
if (_hostEnvironment.IsDevelopment()) {..}
Additionally, you're actually able to implement a filter factory interface just to use [DevOnly] attribute before your controller class.
AAnton11/12/2022
can you elaborate? would I throw in the constructor or something? I don't understand can filters run prior to mapping even? or like while resolving what to map yeah I've seen this post, I'm confused tho
Pplam11/12/2022
After the successful injection of the interface you're pretty much able to check for the environment inside of the body of action.
public class ExampleController : Controller
{
private readonly IHostEnvironment _hostEnvironment;

public ExampleController(IHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}

public IActionResult View()
{
if (!_hostEnvironment.IsDevelopment()) // Return something else for Development.
}
}
public class ExampleController : Controller
{
private readonly IHostEnvironment _hostEnvironment;

public ExampleController(IHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}

public IActionResult View()
{
if (!_hostEnvironment.IsDevelopment()) // Return something else for Development.
}
}
AAnton11/12/2022
would the filter in the second answer run once prior to the mapping being established, or every time no this is not what I want like I said, I don't want it to be mapped at all if it's development this would still map it
Pplam11/12/2022
Stack Overflow
Conditionally disable ASP.NET MVC Controller
What is the best way to disable ASP.NET MVC controller conditionally? I want to have an access to the controller actions if some value in web.config is "true" and 404 if it's "false" Should I wr...
Pplam11/12/2022
There's an answer with an implementation of a filter, go for it It depends
AAnton11/12/2022
This would still map the controller and its actions, I really don't want that Like I'm just tempted to put a #if DEVELOPMENT or something on the class but I see that people don't usually do that in ASP.NET Core Don't know why tho
UUUnknown User11/12/2022
3 Messages Not Public
Sign In & Join Server To View
AAnton11/12/2022
Not debug There should be a separate PRODUCTION that I would define in a production build
UUUnknown User11/12/2022
2 Messages Not Public
Sign In & Join Server To View
AAnton11/12/2022
debug vs production should be two separate concepts that's not what I mean I mean you may still want to build for prodcution in debug mode for testing purposes It's fine, I have a Nuke task doing a production build
Pplam11/12/2022
Why don't you just return NotFound as for the controller which is flagged with attribute for DevOnly or sum
AAnton11/12/2022
because it's a catch all controller I may want to have some other logic for that case, defined somewhere else + it's extra work done for no reason
AAccord11/22/2022
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Looking for more? Join the community!

Want results from more Discord servers?
Add your server
Recommended Posts
❔ Turn off VS 2022 PreviewHow do I turn off VS 2022 Preview? It is showing on the splash screen and everywhere. I turned it on❔ Winforms rotated text in `ToolStripButton` appears boldWhen setting the direction of text to e.g. Vertical270, the text in the button becomes different, eiIf I do console.clear() it just skips a bunch of lines instead of clearingI am using vsc c# and I think its an error with .net because I saw a few forums talking about it, pl❔ Why wont visual studio auto format this with CTRL K + CTRL D?can anyone think of why visual studio wont format these lambda arrows with `CTRL K + CTRL D` but it ❔ Changing TextBlock Background property in a static methodThe method needs to be static (unless there are implementations of LowLevelKeyboardProc that doesn't❔ SQLite with Muai ensure connectionstring to DB for all devicesIm running SQLite db and i want the connection to the DB to point to the same file no matter if i ru❔ IEnumerable is empty for some reasonI want to add a filter to check if an IEnumerable is empty so i'm using IEnumerable.Any(), but my IEMy code is stuck in a infinity loop [Answered]https://github.com/AbdulRaheemNazir/MiniApps/blob/main/Just%20need%20random%20Symbol When I try to ❔ How can I check if any element of a list is in another list?I know i could do it with a for loop, but it seems overkill to do something that simple :/❔ How to parse a json response?.❔ Task.WhenAll for Tests, and other async questionsIn xUnit, there is no support for testing async or in parallel within the same collection, where a cEntity Framework Core DB issues [Answered]Introducing FOREIGN KEY constraint 'FK_Sections_Teachers_TeacherID' on table 'Sections' may cause cy❔ Reverse proxy + controllers ordering issuesPlease help https://github.com/microsoft/reverse-proxy/discussions/792#discussioncomment-4119355❔ where generic is itypea or itypebIs there syntax to check weather a generic attribute is either of two interface types? Pseudo: Wher❔ A question about struct - interface implementationStructs that implement interfaces arent allocated on the heap normally, rather just if being cast to❔ Calculate AreaHi guys! I need some help about a task I've been stuck for a while. I follow a programing course andMy code is stuck in a infinity loophttps://github.com/AbdulRaheemNazir/MiniApps/blob/main/Just%20need%20random%20Symbol When I try to ❔ Blazor WASM PWA clear all cache and update applicationMy app does not update automatically on new versions (I use WASM). Since it's PWA the `no-cache` hea❔ Render HTML classes based on properties (Blazor)So we managed to setup a Linq expression to get all matching tags from two lists and all. Which is a❔ Does WebClient have the same socket exhaustion problem like HttpClient?title