ASP.NET中间件如何调用另一个Action?
创始人
2024-09-19 21:30:41
0

ASP.NET中间件可以通过调用下一个中间件或处理程序来执行以下操作,但是不能直接调用另一个Action。

一种解决方法是使用.NET的HttpClient来请求另一个Controller的Action。以下是示例:

using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

public class MyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly HttpClient _httpClient;

    public MyMiddleware(RequestDelegate next)
    {
        _next = next;
        _httpClient = new HttpClient();
    }

    public async Task Invoke(HttpContext context)
    {
        //调用另一个Controller的Action
        var response = await _httpClient.GetAsync("http://localhost:5000/MyController/MyAction");

        //使用响应内容继续处理
        var content = await response.Content.ReadAsStringAsync();

        await context.Response.WriteAsync("Response from MyController/MyAction: " + content);
    }
}

在此示例中,MyMiddleware使用HttpClient来请求MyController中的MyAction,然后将响应内容写回到Response中。请注意,此方法仅适用于请求不需要当前HttpContext的Action。

如果需要使用当前HttpContext,请使用以下代码示例调用另一个Controller的Action:

public class MyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IServiceProvider _serviceProvider;

    public MyMiddleware(RequestDelegate next, IServiceProvider serviceProvider)
    {
        _next = next;
        _serviceProvider = serviceProvider;
    }

    public async Task Invoke(HttpContext context)
    {
        //使用IServiceProvider获取MyController实例
        var controller = _serviceProvider.GetService(typeof(MyController)) as MyController;

        //调用MyAction,并传递当前HttpContext
        var result = await controller.MyAction(context);

        //使用ActionResult处理结果
        await result.ExecuteResultAsync(new ActionContext { HttpContext = context });
    }
}

public class MyController : Controller
{
    public async Task MyAction(HttpContext context)
    {
        //使用当前HttpContext处理数据
        var data = "Hello from MyController/MyAction using HttpContext";

        return Ok(data);
    }
}

在此示例中,MyMiddleware使用IServiceProvider获取MyController实例,然后调用MyController中的MyAction,并传递当前HttpContext。MyAction中可以对HttpContext进行处理,并使用ActionResult返回结果。MyMiddleware将结果传递给ActionContext并执行结果。

相关内容

热门资讯

透视挂!德普之星辅助器app,... 透视挂!德普之星辅助器app,aa poker透视软件,详细教程(有挂规律)1、许多玩家不知道德普之...
透视工具!wepoker数据分... 透视工具!wepoker数据分析,wepoker可以透视码(透视)微扑克教程(有挂黑科技)该软件可以...
透视规律!wepoker手机助... 透视规律!wepoker手机助手,hhpoker怎么开透视,wpk教程(有挂方法)1、下载好hhpo...
透视免费!wepoker轻量版... 透视免费!wepoker轻量版有透视吗,wepoker有辅助插件吗(透视)2025新版(有挂工具)w...
透视安卓版!we-poker辅... 透视安卓版!we-poker辅助软件教程,拱趴大菠萝挂,解密教程(有挂方法)1、完成we-poker...
透视透视挂!wepoker的辅... 透视透视挂!wepoker的辅助器,wepoker透视最简单三个步骤(透视)玩家教程(有挂工具);1...
透视有挂!wejoker辅助机... 透视有挂!wejoker辅助机器人,大菠萝辅助器,扑克教程(有挂秘笈)wejoker辅助机器人软件透...
透视ai代打!wepoker私... 透视ai代打!wepoker私人局可以透视,wepoker有用吗(透视)wpk教程(有挂解密)在进入...
透视辅助!wepoker私局代... 透视辅助!wepoker私局代打,wepoker私人辅助器,玩家教程(有挂详情)1、下载好wepok...
透视总结!wepokerplu... 透视总结!wepokerplus外挂,wepoker私人局俱乐部辅助(透视)解密教程(有挂揭秘);一...