Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor pages and webapi in the same project

Tags:

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?

like image 727
Gummibear Avatar asked May 24 '19 19:05

Gummibear


People also ask

How do I add an API to my Razor page?

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.

Can you mix Razor pages and MVC?

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.

Why are Razor pages better than MVC?

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.

How do I return the render razor view from Web API controller?

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.


Video Answer


1 Answers

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();         });     } 
like image 97
Ryan Avatar answered Sep 18 '22 12:09

Ryan