如何更改ASP.NET Core API中的默认控制器和动作? [英] How to change the default controller and action in ASP.NET Core API?

查看:672
本文介绍了如何更改ASP.NET Core API中的默认控制器和动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个ASP.NET Core API应用程序,当前,当创建一个新项目时,有一个名为Values的控制器,默认情况下,API在您运行时将其打开.因此,我删除了该控制器,并添加了一个名为Intro的新控制器,并在其中添加了一个名为Get的动作.在Startup.cs文件中,我具有以下代码行:

I'm creating an ASP.NET Core API app, and currently, and when one creates a new project there is a controller named Values, and by default the API opens it when you run. So, I deleted that controller and added a new controller named Intro, and inside it an action named Get. In the Startup.cs file, I have the following lines of code:

app.UseMvc(opt =>
{
    opt.MapRoute("Default",
        "{controller=Intro}/{action=Get}/{id?}");
});

我的Intro控制器如下所示:

And my Intro controller looks like this:

[Produces("application/json")]
[Route("api/[controller]")]
[EnableCors("MyCorsPolicy")]
public class IntroController : Controller
{
    private readonly ILogger<IntroController> _logger;

    public IntroController(ILogger<IntroController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IActionResult Get()
    {
        // Partially removed for brevity
    }
}

但是,再次运行API时,默认情况下它会尝试导航到/api/values,但是由于我删除了Values控制器,现在出现了404 not found错误.如果我手动然后导航到/api/intro,则将获得Intro控制器内部的Get操作提供的结果.如何确保API运行时(例如通过Debug-> Start Without Debugging)在默认情况下从Intro控制器获取Get操作?

But, again when I run the API, it by default tries to navigate to /api/values, but since I deleted the Values controller, now I get a 404 not found error. If I manually then navigate to /api/intro, I get the result that is provided from my Get action inside the Intro controller. How can I make sure that when the API run (for example through Debug->Start Without Debugging) that it by default gets the Get action from the Intro controller?

推荐答案

您可以在Properties节点的launchSettings.json文件中对其进行更改.应该有一个launchUrl字段,其中包含默认的启动URL

You can change it in launchSettings.json file in Properties node. There should be field launchUrl which contains default launching url

这篇关于如何更改ASP.NET Core API中的默认控制器和动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆