【问题标题】:How to call an action with parameters in .net core?如何在.net核心中调用带有参数的动作?
【发布时间】:2020-05-04 12:07:10
【问题描述】:

所以我在 Startup.cs 中设置了以下默认模式:

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

这是我的控制器:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

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

    [HttpGet]
    [Route("[action]")]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 0),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }

    [HttpGet]
    [Route("[action]")]
    public IEnumerable<WeatherForecast> Grab()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(1, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }

    [Route("[action]")]
    [HttpGet("{i:int}")]
    public IEnumerable<WeatherForecast> Snatch(int i)
    {
        var rng = new Random();
        return Enumerable.Range(i, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(55, 100),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

现在,当我调用 https://localhost:44388/weatherforecast/grabhttps://localhost:44388/weatherforecast/get 时,它可以正常工作,但如果我调用 https://localhost:44388/weatherforecast/Snatch/1,我会在浏览器中看到 Error: Cannot match any routes.

我已经设置了最后一个方法 Snatch 与它期望一个 int 的参数,所以我做错了什么?

【问题讨论】:

    标签: c# .net-core asp.net-core-routing


    【解决方案1】:

    您需要使用一个路由模板来获得所需的行为

    //GET weatherforecast/Snatch/1
    [Route("[action]/{i:int}")]
    [HttpGet]
    public IEnumerable<WeatherForecast> Snatch(int i) {
        //...
    }
    

    现在这是一个ApiController,所有操作只使用Http{Verb}就足够了

    在构建 REST API 时,您很少会希望在操作方法上使用 [Route(...)],因为该操作将接受所有 HTTP 方法。最好使用更具体的 Http*Verb*Attributes 来准确了解您的 API 支持什么。 REST API 的客户端应该知道哪些路径和 HTTP 动词映射到特定的逻辑操作。

    //GET weatherforecast/Snatch/1
    [HttpGet("[action]/{i:int}")]
    public IEnumerable<WeatherForecast> Snatch(int i) {
        //...
    }
    

    这可以通过聚合模板进一步简化

    [ApiController]
    [Route("[controller]/[action]")] //<-- NOTE THIS
    public class WeatherForecastController : ControllerBase {
    
        //...
    
        //GET weatherforecast/get
        [HttpGet]
        public IEnumerable<WeatherForecast> Get() {
            //...
        }
    
        //GET weatherforecast/grab
        [HttpGet]
        public IEnumerable<WeatherForecast> Grab() {
            //...
        }
    
        //GET weatherforecast/Snatch/1
        [HttpGet("{i:int}")]
        public IEnumerable<WeatherForecast> Snatch(int i) {
            //...
        }
    }
    

    参考Routing to controller actions in ASP.NET Core

    参考Routing in ASP.NET Core

    【讨论】:

    • 谢谢,我确实找到了您链接的那些参考文献,但我想我误解了它们。所以现在我可以删除其他两种方法中的 Route 属性并安全地使用[HttpGet("[action]")] ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2019-02-16
    • 2019-04-23
    • 2020-09-09
    • 2019-04-02
    • 1970-01-01
    • 2018-10-30
    相关资源
    最近更新 更多