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

给你一囗甜甜゛ 提交于 2019-12-02 02:12:00
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.0The 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 :)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!