简体   繁体   English

在 ASP.Net Core 中添加中间件到 Pipe

[英]Adding Middleware to Pipe in ASP.Net Core

Previously in ASP.Net I would have written a Generic Http Handler to do this but it looks like in ASP.Net Core you write Middleware.以前在 ASP.Net 中,我会编写一个通用 Http 处理程序来执行此操作,但它看起来像在 ASP.Net Core 中你编写中间件。

I am trying to get my Middleware to be called when the page GetUser is requested.我试图在请求页面 GetUser 时调用我的中间件。

I've tried to understand how from this page https://learn.microsoft.com/en-us/as.net/core/fundamentals/middleware/?view=as.netcore-7.0 - but have only got so far.我试图从这个页面https://learn.microsoft.com/en-us/as.net/core/fundamentals/middleware/?view=as.netcore-7.0了解如何 - 但到目前为止。

The Middleware code is as follows;中间件代码如下;

public class GetUser
{
    public GetUser(RequestDelegate next)
    {
        // note this is a handler so no need to store the next
    }

    public async Task Invoke(HttpContext context)
    {
        String response = String.Empty;

        try
        {
            response = GenerateResponse(context);

            context.Response.ContentType = "text/plain";
            context.Response.StatusCode = 200;

            await context.Response.WriteAsync(response);
        }
        catch ( System.Exception ex)
        {
            response = ex.Message;
        }
    }

    public String GenerateResponse(HttpContext context)
    {
        String response = "";

        response = "a response";

        return response;
    }

     
}

public static class GetUserExtension
{
    public static IApplicationBuilder UseGetUser(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<GetUser>();
    }

}

In Program.cs I have added the following line;在 Program.cs 中,我添加了以下行;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

app.Map("/GetUser",GetUserExtension.UseGetUser(builder));

Which fails because builder is a WebApplicationBuilder and not IApplicationBuilder.失败是因为构建器是 WebApplicationBuilder 而不是 IApplicationBuilder。

So how can I use app.Map so that it calls GetUserExtension.UseGetUser when the GetUser Page is requested.那么我如何使用 app.Map 以便它在请求 GetUser Page 时调用 GetUserExtension.UseGetUser。

Make sure your middleware is correctly placed in the program.cs file, which when it is called contains all the resources that it needs to return the request.确保您的中间件正确放置在 program.cs 文件中,该文件在被调用时包含返回请求所需的所有资源。 This is not much but hopes this helps.这并不多,但希望这会有所帮助。

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

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