【问题标题】:How to generate a Url to another controller WebApi core 3.1如何生成到另一个控制器 WebApi 核心 3.1 的 URL
【发布时间】:2020-12-11 01:20:05
【问题描述】:

我正在尝试生成到另一个控制器的链接,我只能创建到同一个控制器。

这在同一个控制器中工作

string uri = Url.Link("T", new { token = "token" });

[Route("Taa", Name = "T")]
public  IActionResult SomeMethod(string token)
  {
      return Ok();
  }

我试过了:

Url.Link("Default", new { Controller = "Account", Action = "Login" });
Url.Route("Default", new { Controller = "Account", Action = "Login" }); (Route Does not exist)

真正的Controller和Action是:Validation和Validate

[HttpGet("validate", Name = "Validate")]
public IActionResult ValidateNewUser(string token)
  {     
      return Ok();
  }

【问题讨论】:

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


【解决方案1】:

你可以使用

Url.Link("Default", new { Controller = "Validation", Action = "Validate", token = "token" });

这是一个演示:

启动(配置):

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

控制器:

[ApiController]
    [Route("[controller]")]
    public class TestController : ControllerBase
    {
        public IActionResult Index()
        {
            var url = Url.Link("Default", new { Controller = "Validation", Action = "Validate", token = "token" });
            return Ok();
        }
    }

网址结果:

https://localhost:xxxx/Validation/Validate?token=token

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多