How to use RoutePrefix in sub folders in Controller folder in .net core 6 Web API Application?

61 views Asked by At

I am trying to call controller action in subfolder located in main Controller folder. I changed RoutePrefix in controller and app.MapControllerRoute() in program.cs different ways. But my postman call still not hitting my target action in controller. I am looking a suitable solution.

program.cs as follows.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();


builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = options.DefaultPolicy;
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
 
}

app.UseDefaultFiles();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();

app.UseCors(x => x
           .AllowAnyMethod()
           .AllowAnyHeader()
           .SetIsOriginAllowed(origin => true) // allow any origin 
           .AllowCredentials());

app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "api/{controller}/{action}/{id}");
app.Run();

My CommonController.cs as follows.

namespace AppWebSerivce.Controllers.CardDetails
{
    [RoutePrefix("api/CardDetails/Common")]
    public class CommonController: ControllerBase
    {
        [HttpPost]
        [Route("v1/GetStringName")]    
        public string StringName()
        {
            string ss = "SS";
            return ss;
        }

    }
}

My Postman call as.

http://localhost:5150/api/CardDetails/Common/v1/GetStringName

Controller path as.

AppWebSerivce -> Controllers -> CardDetails -> CommonController.cs

I am trying to hit controller action in Controllers -> CardDetails -> CommonController.cs using RoutePrefix.

1

There are 1 answers

0
Jason Pan On

We can find RoutePrefixAttribute Class is in Microsoft.AspNet.Mvc package, it means it not support in asp.net core. So we can change the code like below:

using Microsoft.AspNetCore.Mvc;

namespace routeprefix_app.Controllers.CardDetails
{
    [ApiController]
    [Route("api/CardDetails/Common")]
    public class CommonController : ControllerBase
    {
        [HttpPost]
        [Route("v1/GetStringName")]
        public string StringName()
        {
            string ss = "SS";
            return ss;
        }
    }
}

Then we can test it in Swagger or Postman.

enter image description here