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

相关内容

热门资讯

实测发现!忻州天天麻将辅助ai... 实测发现!忻州天天麻将辅助ai透视挂工具,忻州天天麻将一直是有开挂(有辅助挂总结)1、每一步都需要思...
一分钟快速了解!琼戏互娱辅助a... 一分钟快速了解!琼戏互娱辅助ai透视挂软件,琼戏互娱原来真的是有作弊器(有辅助挂规律)1)琼戏互娱免...
技术分享!红中麻将辅助ai透视... 技术分享!红中麻将辅助ai透视挂脚本,红中麻将都是真的有辅助器(有辅助挂工具)红中麻将能透视中分为三...
揭秘关于!亲友房辅助ai透视挂... 揭秘关于!亲友房辅助ai透视挂方法,亲友房总是是有辅助器(有辅助挂技巧)1、亲友房免费脚本咨询教程、...
玩家科普!鄱阳翻精辅助ai透视... 玩家科普!鄱阳翻精辅助ai透视挂脚本,鄱阳翻精原来是有开挂(有辅助挂方针)鄱阳翻精破解侠是真的助透视...
技巧知识分享!奈曼麻将辅助ai... 技巧知识分享!奈曼麻将辅助ai透视挂插件,奈曼麻将确实存在有透视挂(有辅助挂秘笈)该软件可以轻松地帮...
分享开挂内幕!闲来广东麻将辅助... 分享开挂内幕!闲来广东麻将辅助ai透视挂方法,闲来广东麻将原来存在有开挂(有辅助挂细节)1、金币登录...
一分钟揭秘!友聚麻将辅助ai透... 一分钟揭秘!友聚麻将辅助ai透视挂工具,友聚麻将都是是真的有开挂(有辅助挂规律)1、完成友聚麻将辅助...
玩家实测!边锋嘉兴麻将辅助ai... 玩家实测!边锋嘉兴麻将辅助ai透视挂脚本,边锋嘉兴麻将真是有透视器(有辅助挂分享)1、边锋嘉兴麻将透...
免费测试版!友聚麻将辅助ai透... 免费测试版!友聚麻将辅助ai透视挂工具,友聚麻将一直有透视挂(有辅助挂攻略)1、用户打开应用后不用登...