码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2019-10-23 13:21:00      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:min   check   cal   sea   option   cli   read   on()   cookie   

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 :)


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

标签:min   check   cal   sea   option   cli   read   on()   cookie   

原文地址:https://www.cnblogs.com/Bright-Lee/p/11725056.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!