I created a web app (razor pages) in .net core 3.0. Then I added an api controller to it (both from templates, just few clicks). When I run app, razor page works, but api call returns 404. Where is the problem and how can I make it work?
Adding the Web API In order to add a Web API Controller you will need to Right Click the Project in the Solution Explorer and click on Add and then New Item. Now from the Add New Item window, choose the API Controller – Empty option as shown below. Then give it a suitable name and click Add.
You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder.
From the docs, "Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views." If your ASP.NET MVC app makes heavy use of views, you may want to consider migrating from actions and views to Razor Pages.
ASP.NET MVC4 Web API controller should return Razor view as html in json result property. Message=The method or operation is not implemented. var viewResult = ViewEngines.
You need to configure your startup to support web api and attribute routing.
services.AddControllers()
adds support for controllers and API-related features, but not views or pages. Refer to MVC service registration.
Add endpoints.MapControllers
if the app uses attribute routing. Refer to Migrate MVC controllers.
Combine razor pages and api like:
public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; }); services.AddRazorPages() .AddNewtonsoftJson(); services.AddControllers() .AddNewtonsoftJson(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //other middlewares app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); }); }
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