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并执行结果。

相关内容

热门资讯

透视辅助!wepoker透视方... 透视辅助!wepoker透视方法,微乐自建房脚本使用安全吗,了解脚本(有挂总结)-哔哩哔哩wepok...
脚本透视!hhpkoer辅助挂... 脚本透视!hhpkoer辅助挂是真的吗,hhpoker有后台操作吗(透视)确实真的是有挂(哔哩哔哩)...
据玩家消息!wepoker软件... 据玩家消息!wepoker软件安装包,微乐自建房辅助神器怎么安装,教你脚本(确实有挂)-哔哩哔哩1、...
透视攻略!德州局HHpoker... 透视攻略!德州局HHpoker透视脚本,微乐小程序辅助开发透视,有挂脚本(有挂技巧)-哔哩哔哩1、德...
透视开挂!hhpoker辅助,... 透视开挂!hhpoker辅助,hh poker辅助器先试用(透视)其实是真的软件(哔哩哔哩)暗藏猫腻...
透视分享!aapoker辅助器... 透视分享!aapoker辅助器是真的吗,aapoker怎么开辅助器(透视)好像存在有挂(哔哩哔哩)1...
值得注意的是!线上德州的辅助器... 值得注意的是!线上德州的辅助器是什么,广西微乐小程序微信辅助器免费,详情透视(有挂方针)-哔哩哔哩1...
透视了解!aapoker如何设... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在这款游戏中打...
透视攻略!hhpoker软件安... 透视攻略!hhpoker软件安装包,微乐小游戏万能修改器,详情透视(有挂秘诀)-哔哩哔哩亲,关键说明...
透视专业!wpk透视辅助下载,... 透视专业!wpk透视辅助下载,wpk模拟器是什么(透视)好像是真的工具(哔哩哔哩)脚本下载中分为三种...