简体   繁体   English

问题映射新 api controller 添加到 Razor 页面

[英]Problem mapping new api controller added to Razor pages

I have tried adding an API controller to a Razor pages project in.Net core.我尝试将 API controller 添加到 Razor 页面项目中的.Net 核心。 I added a Controllers folder to my project, clicked on add item and chose new controller.我在我的项目中添加了一个 Controllers 文件夹,单击添加项目并选择新的 controller。 The pages run on the local host but when I tried testing the default GET using这些页面在本地主机上运行,但是当我尝试使用测试默认 GET 时

https://localhost:44348/api/ 

in Postman, I get a 404 error.在 Postman 中,我收到 404 错误。

The code Visual Studio generated was: Visual Studio 生成的代码是:

namespace MyWebApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class APIController : ControllerBase
    {
        // GET: api/<APIController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<APIController>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<APIController>
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

    }
}

(I've removed the PUT and DELETE methods). (我已经删除了 PUT 和 DELETE 方法)。 I am not sure how this is mapped.我不确定这是如何映射的。

I assume that the API is running on the same port as the rest of the app.我假设 API 与应用程序的 rest 在同一端口上运行。 Is this correct?这个对吗?

In the mapping "api/[controller]", what should I be putting for [controller].在映射“api/[controller]”中,我应该为 [controller] 放置什么。 Do I need to instantiate an APIController object somewhere?我需要在某处实例化 APIController object 吗?

Any advice would be greatly appreciated!任何建议将不胜感激!

If you want to use an API Controller in razor page project,you can do like this:如果你想在 razor 页面项目中使用 API Controller 页面项目,你可以这样做:

startup.cs:启动.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ...

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

And then if you want to go to Get ,you need to use https://localhost:44348/api/API as Chetan Ranpariya said.然后如果你想 go 来Get ,你需要使用https://localhost:44348/api/API正如Chetan Ranpariya所说。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM