【问题标题】:Enable routing for api endpoints in RazorPages app在 RazorPages 应用程序中为 api 端点启用路由
【发布时间】:2023-04-02 10:58:01
【问题描述】:

无法直接路由到 api 端点。

我的 api 控制器“TestController”应该在 localhost:5511/api/Test/getCollection?testCode=A 找到,但它不会路由并返回 404。

我有一个 .net core 3.0 RazorPages 应用程序,但需要包含一些 api 端点。我认为我的端点没有被路由。 在 Startup.cs 配置方法中我有这个:

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllers();               
});

这是我在控制器上的路由属性:

[Route("api/[controller]/[action]")]

GetCollection 操作:

[HttpGet]
public IActionResult GetCollection(string testCode)
{

    List<string> retval = ...get a string list

    return Ok(retval);
}

[编辑]
-------- 好的一个更简单的例子,不会路由到 api ---------
Razor pages .net core 3.0 应用,添加一个带有控制器的新文件夹 /api

前往
https://localhost:44340/api/lookup/getsomething时收到 404

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }

api 控制器

namespace aspnetcore1.Api
{
    [Route("api/[controller]")]
    [ApiController]
    public class LookupController : ControllerBase
    {

        [HttpGet]
        [Route("GetSomething")]
        public IActionResult GetSomething()
        {
            return Ok("this is a test");
        }
    }
}

【问题讨论】:

    标签: c# asp.net-core razor-pages


    【解决方案1】:

    控制器上的路由属性应该是:

    [Route("api/Test")]

    并且方法上的路由属性应该是:

    [HttpGet]
    [Route("GetCollection")]
    public IActionResult GetCollection(string testCode)
    {
    
        List<string> retval = ...get a string list
    
        return Ok(retval);
    }
    

    编辑

    Configure(IApplicationBuilder app, IWebHostEnvironment env) 方法中似乎缺少此内容:

    app.UseMvc();
    

    【讨论】:

    • 不,仍然无法正常工作。我将包含一个简单的示例,因为我显然遗漏了与如何启用路由相关的内容。
    • 好的,谢谢。我已经设法弄清楚了——创建一个新的纯 API 项目并查看 Starup 是如何配置的
    猜你喜欢
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2019-02-15
    • 2012-08-22
    • 2018-08-01
    • 2021-03-03
    • 2021-09-05
    • 2014-05-04
    相关资源
    最近更新 更多