简体   繁体   English

如何将 Web API controller 添加到现有的 Z9E0DA8438E1E38A1C30F4B76CE3 内核 MVC?

[英]How to add Web API controller to an existing ASP.NET Core MVC?

I created a project using the default ASP.NET Core MVC template.我使用默认的 ASP.NET Core MVC 模板创建了一个项目。 I would like to also create a RESTful API under /api/{Controller} .我还想在/api/{Controller}下创建一个 RESTful API 。 I added a new Web API controller (standard Web API controller class template) but I can't call it. I added a new Web API controller (standard Web API controller class template) but I can't call it. I get an error saying that the page cannot be found.我收到一条错误消息,提示找不到该页面。 I tried adding a route in Startup.cs but it doesn't do anything:我尝试在Startup.cs中添加一条路线,但它什么也没做:

app.UseMvc(routes =>
{
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
});

EDIT:编辑:

Like I said, it's all default templates.就像我说的,这都是默认模板。 Here's the Web API Controller that I added:这是我添加的 Web API Controller:

[Route("api/[controller]")]
public class AdminController : Controller
{                
    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

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

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

Two things.两件事。

First, when using convention-based routing, more specific routes should come before more generic routes to avoid route conflicts.首先,当使用基于约定的路由时,更具体的路由应该放在更通用的路由之前,以避免路由冲突。

app.UseMvc(routes =>
{
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
});

Secondly, you are already using attribute routing on the controller so should have been able to route to the controller except for the fact that you do not have a routing template on the controller that would accept /api/{Controller}其次,您已经在控制器上使用属性路由,因此应该能够路由到控制器,除非您在控制器上没有接受/api/{Controller}的路由模板

That would require a default route.那将需要一个默认路由。

[Route("api/[controller]")]
public class AdminController : Controller {
 
    [HttpGet("")] //Matches GET api/admin <-- Would also work with [HttpGet]
    public IActionResult Get() {
        return Ok();
    }

    [HttpGet("{id}")] //Matches GET api/admin/5
    public IActionResult Get(int id) {
        return Ok("value");
    }    

    //...other code removed for brevity
}

If someone still have problem in adding webapi to .net core MVC, just inserting [ApiController] and [Route("api/[controller]")] attributes before class solves the problem:如果有人在将 webapi 添加到 .net core MVC 时仍然有问题,只需在 class 之前插入[ApiController][Route("api/[controller]")]属性即可解决问题:

[Route("api/[controller]")]
[ApiController]
public class ListController
{ ... }

I didn't added a route mapping in Startup.cs and still working well.我没有在Startup.cs添加路由映射,但仍然运行良好。 The version of .net that I am using is 2.1.402我使用的 .net 版本是 2.1.402

After updating to the latest version of ASP.NET Core, v2.0.1 (the one that needs VS2017), the problem resolved itself.更新到最新版本的ASP.NET Core v2.0.1(需要VS2017的那个)后,问题自行解决。 I think it was probably a bug or shortcoming in the old version.我认为这可能是旧版本中的错误或缺点。

I had luck doing this with v3.1:我很幸运用 v3.1 做到了这一点:

Add Folder Controllers to the project.将文件夹控制器添加到项目中。 Add Controller , named TestController, to the folder.将名为 TestController 的Controller添加到文件夹中。 Then add the following to the Startup.cs:然后将以下内容添加到 Startup.cs:

services.AddControllers();

to

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

and:和:

endpoints.MapControllers();

to

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

Then I was able to call /api/Test.然后我就可以调用/api/Test。

Try setting name to "Admin"尝试将名称设置为“管理员”

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "Admin",
                template: "api/{controller=Admin}");
        });

Running existing .net core MVC:运行现有的 .net 核心 MVC:

In order to add api controllers to existing .net core 6 mvc application, Open Program.cs file, add following codes:为了将 api 控制器添加到现有的 .net 核心 6 mvc 应用程序,打开 Program.cs 文件,添加以下代码:

//for apis
builder.Services.AddRazorPages();
builder.Services.AddControllers();

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

Now go ahead and add a new controller:现在前面是 go 并添加一个新的 controller:

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    //endpoint: http://localhost:5207/api/test/strings
    [HttpGet("strings")]
    public IActionResult TestMethod()
    {
        return Ok(new string[]{ 
        "23", "24"});
    }
}

Testing Endpoint here This works for me in .net core 6在此处测试端点这在 .net 核心 6 中对我有用

暂无
暂无

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

相关问题 如何将 web api 添加到现有的 asp.net mvc core 6 web 应用程序 - How do i add a web api to an existing asp.net mvc core 6 web application 如何将Web API添加到现有的ASP.NET MVC(5)Web应用程序项目? - How to add Web API to an existing ASP.NET MVC (5) Web Application project? 我可以将 ASP.NET Core MVC 添加到现有的 ASP.NET Web Z645024253191A381C36Z83CAE8 - Can I add ASP.NET Core MVC to existing ASP.NET Web Forms Application 如何防止ASP.NET Core MVC App Web API Controller中的CSRF / XSRF - How-to prevent CSRF / XSRF in ASP.NET Core MVC App Web API Controller 现有ASP.NET Web API中的ASP.NET MVC 4 - ASP.NET MVC 4 in existing ASP.NET Web API 如何避免循环引用asp.net core mvc [HttpPost(&quot;add-recipe&quot;)] web api - How to avoid the circular referencing asp.net core mvc [HttpPost("add-recipe")] web api 如何从 ASP.NET 核心 mvc 向 ASP.NET 核心中的 Web API 发出 PUT 请求? - How to make a PUT request from ASP.NET core mvc to Web API in asp.net core? 如何将ASP.NET MVC核心视图和ASP.NET WEB API控制器分离到单独的项目中? - How to seperate ASP.NET MVC core view and ASP.NET WEB API controllers into separate projects? 如何使 PUT 从 ASP.NET MVC 到 ASP.NET 核心 Web ZDB974238714CA8A44A7CE1D0? - How to make PUT from ASP.NET MVC to ASP.NET Core Web API? 如何在同一项目中的ASP.NET MVC控制器中从ASP.NET Web API获取数据 - How get data from asp.net web api in asp.net mvc controller in the same project
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM