c# - 无法命中任何 API 方法
问题描述
我有这个控制器:
[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();
}
}
我的创业班:
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();
}
}
我一直在尝试与邮递员打交道:
localhost.../api/users/getusers
但无法命中任何方法。
我创建了一个示例控制器,但仍然无法使用该方法。
从邮递员发送请求后,总是找不到 404。我知道这意味着我正在寻找的资源不存在。
解决方案
尝试http://localhost:port/api/users
[HttpGet]
使它使用http get方法,它没有将动作名称添加到路由中,因此路由仍然只是控制器的基本路由。[HttpGet("[action]")]
如果您愿意,请使用。
对于第二个动作,您可能希望[HttpGet("{id}")]
能够使用/api/users/123
推荐阅读
- javascript - 无法读取 TS 中未定义的属性“创建”
- shell - 从 Dataproc 集群执行 Spark 作业时,执行程序检测信号在 125009 毫秒后超时
- mongodb - 将数据从胶水加载到雪花
- swift - 如何在 Swift 中自定义 Firebase 身份验证 UI
- javascript - Jquery通过随机div切换
- c++ - 有没有办法获得模板提供的尺寸类型?
- reactjs - console.log(this.props.store) 在我的创建反应应用程序中返回未定义?
- coinbase-api - 请求访问令牌 API 密钥
- asp.net-mvc - 我可以像 Windows 窗体中的 MS Gridview 一样处理 DevExpress GridView 吗?
- c++ - 如何对复杂的模板化函数进行显式实例化?和相关的智能感知错误