Use Razor pages and webapi in the same project @ .net core 3.0

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.
I get the answer on stackoverflow:https://stackoverflow.com/questions/56298701/razor-pages-and-webapi-in-the-same-project;
here is the code:
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(); }); }
The question is solved;
After this,I want add a custon AuthorzationMiddleWare to the pipeline both invoked in razor pages and webapis,but it only works in webapi actually ;
here is the code:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}

app.UseSession();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});

app.UseCookiePolicy();

app.UseMiddleware(typeof(DkmsAuthorzationMiddleWare));//this is the custom middelware;
}

I read the Official documents about middleware;https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.0

The Mvc pipeline is composed by a series of middlewars,and the middlewars are sorted,the sort depending on when we use the middle in Configure Method;
so I move the app.UseMiddleware(typeof(DkmsAuthorzationMiddleWare)) front to app.UseRouting(),because app.UseRouting route the request to razor pages or webapis;
Ok,
AuthorzationMiddleWare to the pipeline both invoked in razor pages and webapis :)


Guess you like

Origin www.cnblogs.com/Bright-Lee/p/11725056.html