我正在嘗試從此鏈接構建 ASP.NET Core Web API(https://docs.microsoft.com/en-us/azure/notification-hubs/push-notifications-android-specific-users-firebase-cloud-訊息)。它希望我使用以下代碼注冊 MessageHandler:
config.MessageHandlers.Add(new AuthenticationTestHandler());
它說“在Program.cs檔案中 Register 方法的末尾添加以下代碼。Program.cs檔案中沒有 register 方法。我發現的所有內容都表明 Register 方法是一個名為的類的一部分WebApiConfig,但是我也沒有這些,當我創建一個時,它找不到HttpConfiguration。如何注冊MessageHandler?
uj5u.com熱心網友回復:
在 ASP.NET Core 中,相當于 a 的MessageHandler是中間件。我轉換AuthenticationTestHandler為中間件:
AuthenticationTestMiddleware.cs:
public class AuthenticationTestMiddleware
{
private readonly RequestDelegate _next;
public AuthenticationTestMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var authorizationHeader = context.Request.Headers["Authorization"].FirstOrDefault();
if (authorizationHeader != null && authorizationHeader
.StartsWith("Basic ", StringComparison.InvariantCultureIgnoreCase))
{
string authorizationUserAndPwdBase64 =
authorizationHeader.Substring("Basic ".Length);
string authorizationUserAndPwd = Encoding.Default
.GetString(Convert.FromBase64String(authorizationUserAndPwdBase64));
string user = authorizationUserAndPwd.Split(':')[0];
string password = authorizationUserAndPwd.Split(':')[1];
if (VerifyUserAndPwd(user, password))
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user)
};
var claimsIdentity = new ClaimsIdentity(
claims: claims,
authenticationType: "password");
context.User.AddIdentity(claimsIdentity);
await _next(context);
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
}
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
}
}
private bool VerifyUserAndPwd(string user, string password)
{
// This is not a real authentication scheme.
return user == password;
}
}
現在Program.cs您可以像這樣注冊:
app.UseMiddleware<AuthenticationTestMiddleware>();
我發現有關轉換MessageHandler為中間件的問題:
從 ASP.NET 到 .NET Core 的 DelegateHandler
在 ASP.NET Core Web API 中注冊一個新的 DelegatingHandler
asp.net core web api中是否有類似于DelegatingHandler的類?
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-6.0
編輯:
找到了一個為 ASP.NET Core 更新的官方示例:
https://github.com/Azure/azure-notificationhubs-dotnet/tree/main/Samples/WebApiSample/WebApiSample
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/503940.html
