Currently I have a web api project that I want to add an admin page that can create users and modify permissions, however there appears to be virtually no documentation on how to add MVC to an existing web api project.
Luckily, the answer is yes. Combining ASP.NET Webforms and ASP.NET MVC in one application is possible—in fact, it is quite easy. The reason for this is that the ASP.NET MVC framework has been built on top of ASP.NET.
For anyone using .Net Core 3, configure your Startup.cs with this template.
Note, I have commented out the existing Web Api code.
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.AddControllers();
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
//endpoints.MapControllers();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Modify ConfigureServices
method in Startup.cs and add this line:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
Modify Configure
method in Startup.cs and add default map route:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I had a similar Problem with a Project using WebApi but not MVC and used the following Approach to add MVC later on:
Once I started the project, it resulted in me getting the following error message:
The view must derive from WebViewPage, or WebViewPage<TModel>
And with that done I could use the standard MVC Controllers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With