如何设置带有查询字符串的自定义URL以操作路由.net核心

问题描述

 [Route("/xxx-xxxx")]
    public IActionResult GoToXxxx()
    {
      return View();
    }

这是我上面的代码,我想设置另一条路线,例如:

 [Route("/xxx-xxxx?l=1")]

我可以使用.net中的RoutePrefix来做到这一点,但是在.net核心中,我不知道该怎么做。

解决方法

两种解决方案:

1。使用http://localhost:35035/xxx-xxxx/{lValue here}

[Route("/xxx-xxxx/{l:int}")]
    public IActionResult GoToXxxx(int l)
    {
      return View();
    }

这是一个演示:

控制器:

[Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        [Route("GetUser/{l:int}")]
        public IActionResult Index(int l)
        {
            return Ok();
        }
    }

测试网址:

https://localhost:44379/api/User/GetUser/1

结果: enter image description here

2。http://localhost:35035/xxx-xxxxhttp://localhost:35035/xxx-xxxx?l={lValue}都将执行操作

[Route("/xxx-xxxx")]
    public IActionResult GoToXxxx(string id)
    {
      return View();
    }
,

您可以这样做:


// xxx-xxxx => GetUser
// l => name

[HttpGet("GetUser/{name}")]
public string GetUser(string name)
{
    return "Hi" + name;
}

这将像这样工作:

http:// localhost:35035 / api / user / GetUser?name = erol