我使用API製作網站時,API需要驗證,因此用戶只能獲取自己的數據。我已經編寫了以下中間件來驗證登錄。.net-core中間件返回空白結果
public class ApiAuthenticationMiddleware
{
private readonly RequestDelegate _next;
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public ApiAuthenticationMiddleware(RequestDelegate next,
SignInManager<ApplicationUser> signInManager,
UserManager<ApplicationUser> usermanager)
{
_next = next;
_signInManager = signInManager;
_userManager = usermanager;
}
public async Task Invoke(HttpContext context)
{
if (!context.Request.Query.ContainsKey("password") || !context.Request.Query.ContainsKey("email"))
{
context.Response.StatusCode = 401; //UnAuthorized
await context.Response.WriteAsync("Invalid User Key");
return;
}
var email = context.Request.Query["email"];
var password = context.Request.Query["password"];
var result = await _signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure: false);
if (result.Succeeded)
{
await _next.Invoke(context);
}
else if (//some more checks)
context.Response.StatusCode = 401; //UnAuthorized
await context.Response.WriteAsync("Invalid User Key");
return;
}
}
}
我想的是,如果用戶沒有有效的登錄顯示空白頁或「無效的用戶密鑰」的錯誤消息。然而,目前發生的是主頁返回(因爲我的中間件在usemvc之前調用,並且return語句跳過由usemvc完成的控制器請求)。
我在startup.cs的配置方法相關的代碼
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseIdentity();
app.UseWhen(x => (x.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)),
builder =>
{
builder.UseMiddleware<ApiAuthenticationMiddleware>();
});
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
我怎樣才能讓我的中間件返回一個空白頁,狀態碼?
請解釋downvoting的原因,以便我可以改善問題,並知道我做錯了什麼。
更新
嘗試了很多事情之後,我發現,當我刪除:
context.Response.StatusCode = 401; //UnAuthorized
它能正常工作,用戶獲得給出的消息:
await context.Response.WriteAsync("Invalid User Key");
Howerver我不希望用戶在登錄失敗時獲得200狀態碼,而是獲得401狀態碼。但是,當使用狀態碼行時,用戶將被重定向。那麼我怎樣才能發送狀態碼而不用重定向呢?
爲什麼不使用'Authorize'屬性 – CodeNotFound
授權假定在用戶登錄(經由餅乾如果即時通訊正確)進出口製造用於移動應用的API,因此該應用將它需要從一個有效的用戶的請求。如果沒有登錄,授權將重定向到註冊頁面,這不是我想要的API行爲。 –
我會看看OpenId中間件。這個中間件使用授權屬性 –