locked
ASP.NET Core 3 Web API Configurations from starting Empty Template RRS feed

  • Question

  • User1518508822 posted

    Created two asp.net core 3 web API applications using empty template and web API template. but one application doesn't get hit request in to controllers created using empty template. I added all the web API configurations using existing web API template. but it doesn't resolve the problem. cant put a request for empty template (added configurations into) controller either using browser or postman. so what are the configurations for web API template for putting request to controller using empty template ?

    Thursday, October 24, 2019 1:10 PM

Answers

  • User475983607 posted

    Add two lines of code to use Web API controllers.

        public class Startup
        {
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseRouting();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    endpoints.MapGet("/", async context =>
                    {
                        await context.Response.WriteAsync("Hello World!");
                    });
                });
            }
        }

    Create a new Controllers folder (optional) and add a Default Controller.

        [Route("api/[controller]")]
        [ApiController]
        public class DefaultController : ControllerBase
        {
            // GET: api/Default
            [HttpGet]
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            // GET: api/Default/5
            [HttpGet("{id}", Name = "Get")]
            public string Get(int id)
            {
                return "value";
            }
    
            // POST: api/Default
            [HttpPost]
            public void Post([FromBody] string value)
            {
            }
    
            // PUT: api/Default/5
            [HttpPut("{id}")]
            public void Put(int id, [FromBody] string value)
            {
            }
    
            // DELETE: api/ApiWithActions/5
            [HttpDelete("{id}")]
            public void Delete(int id)
            {
            }
        }

    Invoke the HTTP Get Action of the Default controller.

    https://localhost:xxxxx/api/default

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 24, 2019 6:55 PM

All replies

  • User475983607 posted

    so what are the configurations for web API template for putting request to controller using empty template ?

    Rather than using the empty template create a new project that uses the Web API template and simply review the template files.

    Thursday, October 24, 2019 1:20 PM
  • User1518508822 posted

    mgebhard

    So what is purpose of providing empty template ? we can create web API applications using asp.net core 2 adding configurations for empty template. there should be a meaning for every code line. there are no any documentation for this ?

    Thursday, October 24, 2019 2:05 PM
  • User475983607 posted

    It takes a few seconds to create a Web API project and review the source.  Not sure why you are not open to this path considering it's quicker than posting on the forum.  Seems silly to post the same code here but it is...

    Program

        public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    });
        }

    Startup

        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseHttpsRedirection();
    
                app.UseRouting();
    
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
        }

    Sample controller

        [ApiController]
        [Route("[controller]")]
        public class WeatherForecastController : ControllerBase
        {
            private static readonly string[] Summaries = new[]
            {
                "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
            };
    
            private readonly ILogger<WeatherForecastController> _logger;
    
            public WeatherForecastController(ILogger<WeatherForecastController> logger)
            {
                _logger = logger;
            }
    
            [HttpGet]
            public IEnumerable<WeatherForecast> Get()
            {
                var rng = new Random();
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                .ToArray();
            }
        }

    If you are looking for details on ASP.NET Core DI, middleware, and general configuration then read through the Fundamentals documentation.  I must have read these docs 100s of times.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/?view=aspnetcore-3.0&tabs=windows

    Thursday, October 24, 2019 2:40 PM
  • User1518508822 posted

    mgebhard

    I don't read 100s times. But I will suggest this to you. Simply create empty asp.net core 3 web API application using empty template. add mentioned piece of codes to this project. navigate https://localhost:44344/weatherforecast. if you get response please mention it. if you don,t get response please mention it. then we can discuss what is missing.

    Thursday, October 24, 2019 3:45 PM
  • User475983607 posted

    michale.p

    mgebhard

    I don't read 100s times. But I will suggest this to you. Simply create empty asp.net core 3 web API application using empty template. add mentioned piece of codes to this project. navigate https://localhost:44344/weatherforecast. if you get response please mention it. if you don,t get response please mention it. then we can discuss what is missing.

    I created an empty ASP.NET Core application and it worked exactly as expected.  The response is Hello World! due to the middleware endpoint routing.

                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapGet("/", async context =>
                    {
                        await context.Response.WriteAsync("Hello World!");
                    });
                });

    The fundamentals are covered in the official documentation.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-3.0

    Thursday, October 24, 2019 5:46 PM
  • User1518508822 posted

    mgebhard

    I believe that there is no code differences between us. But i am getting error as initializing in the url "about:blank" to "https://localhost:44382/WeatherForecast". The error was "This local host page can't be found". I will upload code GitHub tomorrow.

    "

    Thursday, October 24, 2019 6:34 PM
  • User475983607 posted

    mgebhard

    I believe that there is no code differences between us. But i am getting error as initializing in the url "about:blank" to "https://localhost:44382/WeatherForecast". The error was "This local host page can't be found". I will upload code GitHub tomorrow.

    "

    A 404 (Not Found) is the expected result because WeatherForecast does not exist in the empty template.  However, WeatherForecast does exist in the Web API template.  I do not understand why you refuse to create a Web API project for learning purposes. 

    Thursday, October 24, 2019 6:42 PM
  • User475983607 posted

    Add two lines of code to use Web API controllers.

        public class Startup
        {
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseRouting();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    endpoints.MapGet("/", async context =>
                    {
                        await context.Response.WriteAsync("Hello World!");
                    });
                });
            }
        }

    Create a new Controllers folder (optional) and add a Default Controller.

        [Route("api/[controller]")]
        [ApiController]
        public class DefaultController : ControllerBase
        {
            // GET: api/Default
            [HttpGet]
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
            // GET: api/Default/5
            [HttpGet("{id}", Name = "Get")]
            public string Get(int id)
            {
                return "value";
            }
    
            // POST: api/Default
            [HttpPost]
            public void Post([FromBody] string value)
            {
            }
    
            // PUT: api/Default/5
            [HttpPut("{id}")]
            public void Put(int id, [FromBody] string value)
            {
            }
    
            // DELETE: api/ApiWithActions/5
            [HttpDelete("{id}")]
            public void Delete(int id)
            {
            }
        }

    Invoke the HTTP Get Action of the Default controller.

    https://localhost:xxxxx/api/default

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 24, 2019 6:55 PM