How can I focus a controller only works on localhost?

melon NG 296 Reputation points
2022-03-21T08:27:57.147+00:00

I have a site with a controller with so many post and get methods.

Recently, this site will be available to all people. However, I want to maintain this controller only working on localhost.

In spite of this I can add logic to every method, for example:

if (HttpContext.Request.Host.Host.ToLower() != "localhost")
            {
                return NotFound();
            }

I need to add the code above to the method one by one, it is so troublesome.

Is there any way I focus a controller only works on localhost?

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2022-03-22T05:46:48.51+00:00

    Hi @melon NG ,

    According to your description, I suggest you could consider writing a custom middleware to achieve your requirement. This middleware will check every request's host name and path value, if it find the host name is localhost and it wants to access the specific controller, then you could directly return the response.

                app.Use(async (context, next) =>  
                {  
                    if (context.Request.Host.Host.ToLower() != "localhost" && context.Request.Path.Value.Contains("WeatherForecast"))  
                    {  
                        await context.Response.WriteAsync("test");  
                     }  
                    else  
                    {  
                        await next.Invoke();  
                    }  
      
                  
      
                });  
    

    More details about how to use middleware, you could refer to this article.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.