Search code examples
c#asp.netapiasp.net-corerazor

Problem mapping new api controller added to Razor pages


I have tried adding an API controller to a Razor pages project in .Net core. I added a Controllers folder to my project, clicked on add item and chose new controller. The pages run on the local host but when I tried testing the default GET using

https://localhost:44348/api/ 

in Postman, I get a 404 error.

The code Visual Studio generated was:

namespace MyWebApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class APIController : ControllerBase
    {
        // GET: api/<APIController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<APIController>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<APIController>
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

    }
}

(I've removed the PUT and DELETE methods). I am not sure how this is mapped.

I assume that the API is running on the same port as the rest of the app. Is this correct?

In the mapping "api/[controller]", what should I be putting for [controller]. Do I need to instantiate an APIController object somewhere?

Any advice would be greatly appreciated!


Solution

  • If you want to use an API Controller in razor page project,you can do like this:

    startup.cs:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                ...
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapRazorPages();
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
    

    And then if you want to go to Get,you need to use https://localhost:44348/api/API as Chetan Ranpariya said.