I am new to Web API and .net core, and I have a task to develop an API.
So I have created a default web API (framework: .NET Core 2.1) and tried adding the route map and i am getting an error.
guys can someone help me with routing.
Note: Cant use attribute based routing need to handle routes based on a convention like in MVC
My startup program:
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Values", action = "dummyaction" });
});
}
}
And this is the error i am getting:
InvalidOperationException: Action 'myproject.Controllers.ValuesController.dummyaction (myproject)' does not have an attribute route. Action methods on controllers annotated with ApiControllerAttribute must be attribute routed.
How I got it working
even after using map route I was still getting the error which talks about attribute-based routing
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Values", action = "dummyaction" });
});
So in the error can you see this line "Action methods on controllers annotated with ApiControllerAttribute must be attribute routed."
Now in my controller, I was using this particular annotation/attribute "[ApiController]" by removing that I was able to perform convention-based routing.
also, I have updated the route as below
app.UseMvc(routes =>
{
routes.MapRoute(
name: "api",
template: "api/{controller=Values}/{action=gogogo}/{id?}");
});
references:
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.2#mixed-routing-attribute-routing-vs-conventional-routing section(Mixed routing: Attribute routing vs conventional routing)