简体   繁体   中英

How to generate a Url to another controller WebApi core 3.1

I'm trying to generate a link to another controller, I was only able to create to the same controller.

This works in the same controller

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

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

I tried:

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

The real Controller and Action are: Validation and Validate

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

You can use

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

Here is a demo:

startup(Configure):

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

Controller:

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

url result:

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM