【问题标题】:Get request outside a controller in .netcore在.net核心的控制器之外获取请求
【发布时间】:2026-02-19 15:20:03
【问题描述】:

有没有一种方法可以在不使用控制器的情况下从方法中获取响应。我的意思是,为了从数据库中获取租户,我使用属性绑定并从以下位置获取它:“http://localhost:5000/api/tenants”。有没有一种方法可以在不使用控制器(如服务)的情况下检索值?例如,在 Angular 中,我使用 httpclient 来获取响应。 .netcore 2 webapi中有类似的东西吗?谢谢你!

【问题讨论】:

    标签: asp.net-core .net-core asp.net-core-webapi


    【解决方案1】:

    对于Controller,它使用UseMvc middleware 将请求路由到控制器。

    如果您不使用控制器,您可以尝试自定义中间件,直接根据请求路径返回数据。

        public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //your config
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
           //your config
            app.Map("/tenants", map => {
                map.Run(async context => {
                    var dbContext = context.RequestServices.GetRequiredService<MVCProContext>();
                    var tenants = await dbContext.Users.ToListAsync();
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(tenants));
                });
            }); 
            app.Run(async context => {
                await context.Response.WriteAsync($"Default response");
            });          
        }
    }
    

    【讨论】:

      最近更新 更多