简体   繁体   English

在 Program.cs 中注册 MessageHandler

[英]Register MessageHandler in Program.cs

I am trying to build the ASP.NET Core Web API from this link ( https://docs.microsoft.com/en-us/azure/notification-hubs/push-notifications-android-specific-users-firebase-cloud-messaging ). I am trying to build the ASP.NET Core Web API from this link ( https://docs.microsoft.com/en-us/azure/notification-hubs/push-notifications-android-specific-users-firebase-cloud-messaging ) . It wants me to register the MessageHandler using the following code:它希望我使用以下代码注册 MessageHandler:

config.MessageHandlers.Add(new AuthenticationTestHandler());

It says to "add the following code at the end of the Register method in the Program.cs file. There is no register method in the Program.cs file. Everything I have found indicates that the Register method is part of a class called WebApiConfig , but I don't have one of those either, and when I create one, it cannot find HttpConfiguration. How do I register the MessageHandler?它说“在Program.cs文件中 Register 方法的末尾添加以下代码。Program.cs文件中没有 register 方法。我发现的所有内容都表明 Register 方法是 class 的一部分,称为WebApiConfig ,但是我也没有,创建的时候找不到HttpConfiguration,请问如何注册MessageHandler?

In ASP.NET Core the equivalent to a MessageHandler is middleware.在 ASP.NET Core 中,相当于MessageHandler的是中间件。 I converted AuthenticationTestHandler to middleware:我将AuthenticationTestHandler转换为中间件:

AuthenticationTestMiddleware.cs: 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;
    }
}

Now in Program.cs you can register like this:现在在Program.cs中,您可以像这样注册:

app.UseMiddleware<AuthenticationTestMiddleware>();

Questions I found regarding converting MessageHandler to middleware:我发现关于将MessageHandler转换为中间件的问题:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-6.0 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-6.0

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

相关问题 将依赖项传递给 .NET 6 中 program.cs 中的 app.[Methods()] - Pass dependency to app.[Methods()] in program.cs in .NET 6 在 program.cs dotNet Core 6 中添加配置服务 - add configuration services in program.cs dotNet Core 6 如何返回在 Program.cs ASP.Net core 6 中找不到 - How to return not found in Program.cs ASP.Net core 6 如何在 Program.cs 中使用 Mediator 获取 Jwt.IssuerSigningKey? - how to get Jwt.IssuerSigningKey using Mediator in Program.cs? 如何检索Program.cs中返回的访问令牌以在Startup.cs中可用? - How do I retrieve an access token returned in Program.cs to be available in Startup.cs? ASP.NET 内核在 Program.cs 和 Startup.cs 中捕获并显示错误 - ASP.NET Core catch and display error inside Program.cs and Startup.cs ASP.NET Core 6 如何在 Program.cs 中的 builder.Build() 之前访问 IWebHostEnvironment - ASP.NET Core 6 how to access IWebHostEnvironment before builder.Build() in Program.cs 在ASP.NET Core中,有没有办法从Program.cs设置中间件? - in ASP.NET Core, is there any way to set up middleware from Program.cs? Lambda表达式在Razor页面的Program.cs文件中如何工作? - How does the lambda expression work in Program.cs file of Razor pages? 在 ASP.NET 6 的脚手架区域的 program.cs 中添加“app.MapControllerRoute”的正确方法是什么? - What is the right way to add 'app.MapControllerRoute' in program.cs of a Scaffolded Area in ASP.NET 6?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM