Search code examples
c#asp.net-corewebapi

why Can't i hit any API GET method through postman


I have this Controller:

[Route("api/[controller]")]
public class UsersController : Controller
{
    private readonly IDatingRepository _repo;

    public UsersController(IDatingRepository repo)
    {
        _repo = repo;
    }

    [HttpGet]
    public async Task<IActionResult> GetUsers()
    {
        var users = await _repo.GetAllUsers();
        return Ok(users);
    }

    [HttpGet]
    public async Task<IActionResult> GetUser(int id)
    {
        var user = await _repo.GetUser(id);
        if (user != null)
            return Ok(user);
        return NoContent();
    }
}

My startup class:

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)
    {
        var key = Encoding.ASCII.GetBytes("super secret key");
        services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddTransient<Seed>();
        services.AddCors();
        services.AddMvc();
        services.AddScoped<IAuthRepository, AuthRepository>();
        services.AddScoped<IDatingRepository,DatingRepository>();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seed seeder)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else{
            app.UseExceptionHandler(builder => {
                builder.Run(async context => {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if(error != null)
                    {
                            context.Response.AddApplicationError(error.Error.Message);
                        await context.Response.WriteAsync(error.Error.Message);
                    }
                });
            });
        }
        //seeder.SeedUser();
        app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
        app.UseAuthentication();
        app.UseMvc();
    }
}

I have been trying to hit with postman:

localhost.../api/users/getusers

But unable to hit any of the method.
I have created a sample controller but still cannot hit the method.
upon sending a request from postman always getting 404 not found. I know it means that resource i am looking for doesn't exists.


Solution

  • Try http://localhost:port/api/users

    The [HttpGet] makes it use the http get method, it doesn't add the action name to the route, so the route is still just the base route of the controller. Use [HttpGet("[action]")] if you want that.

    For the 2nd action, you probably want [HttpGet("{id}")] to be able to use /api/users/123