简体   繁体   English

ASP.NET Core 应用程序的 Configure 方法中是否有强制的语句顺序?

[英]Is there a mandatory order of statements in the Configure method of a ASP.NET Core application?

Preface:前言:

I spent the whole afternoon trying to understand why my application was always returning a 401 unauthorized response to my requests.我花了整个下午试图理解为什么我的应用程序总是对我的请求返回401 未经授权的响应。

After much much digging, hair pulling and swearing, I came across this question , and this answer :经过多次挖掘,拉头发和咒骂,我遇到了这个问题,以及这个答案

putting app.UseAuthentication();app.UseAuthentication(); before of app.UseAuthorization();app.UseAuthorization();之前app.UseAuthorization(); solves the problem.解决了这个问题。

In my case I saw that I was still receiving some CORS errors (that were not happening if I removed the [Authorize] attribute) so I moved app.UseCors(AllowSpecificOriginsPolicy);就我而言,我看到我仍然收到一些 CORS 错误(如果我删除了[Authorize]属性,则不会发生这种情况),所以我移动了app.UseCors(AllowSpecificOriginsPolicy); first and everything worked!首先,一切正常!

The working order is:工作顺序是:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseCors(AllowSpecificOriginsPolicy); // this one first
    app.UseAuthentication(); // this one second
    app.UseAuthorization(); // this one third
    ...
}

Question:题:

My question is, how do we know what is the right order here?我的问题是,我们怎么知道这里的正确顺序是什么?
Is it written somewhere in the documentation or you just find it with trial and error?它是写在文档中的某个地方还是您只是通过反复试验才找到的?

This information was recently added to the docs , in the form of an example Configure implementation:此信息最近以示例Configure实现的形式添加到docs中:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); // app.UseCookiePolicy(); app.UseRouting(); // app.UseRequestLocalization(); // app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); // app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }

Note that:注意:

Middleware that is not added when creating a new web app with individual users accounts is commented out.使用个人用户帐户创建新 Web 应用程序时未添加的中间件已注释掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM