Max_Power89
Max_Power89

Reputation: 1770

Asp net, how to pass a URL as a url paramter

I'm new to ASP Net and I'm having a little trouble passing a URL as a simple parameter. These are the solutions that I've tried:

     [ApiController]
[Route("api/[controller]")]
public class LoginRedditController : ControllerBase
{        
    [HttpGet("{*longUrl}")]
    public ActionResult<string> Get(string longUrl)
    {
        Console.WriteLine(longUrl);
        return "OK";
    }
}

This is the URL that I've tried to call:

http://localhost:5001/LoginReddit?longUrl=https://www.reddit.com/r/playmygame/comments/glftsj/stickn_roll_collect_everything_as_you_roll/

I also tried to encode the URL but the result is the same: I got a "ERR_EMPTY_RESPONSE" This is my second try:

    [ApiController]
[Route("api/[controller]")]
public class LoginRedditController : ControllerBase
{        
    [HttpGet]
    public ActionResult<string> Get([FromQuery]string url)
    {
       Console.WriteLine(longUrl);
       return "OK";
    }
}

I used the same URL used before but I got the same result.

In my tried try I changed the Route like this:

    [Route("api/[controller]/{url}")]
    public class LoginRedditController : ControllerBase
{        
    [HttpGet]
    public ActionResult<string> Get([FromQuery]string url)
    {
        Console.WriteLine(longUrl);
        return "OK";      
    }
}

And I've tried with the following URL:

http://localhost:5001/LoginReddit/https://www.reddit.com/r/playmygame/comments/glftsj/stickn_roll_collect_everything_as_you_roll/

Also encoded but I got the same resoult.

Where is the problem guys?

Upvotes: 0

Views: 122

Answers (2)

poke
poke

Reputation: 387527

For a URL like this:

http://localhost:5001/LoginReddit?longUrl=https://www.reddit.com/…

You would write your controller action like this:

[ApiController]
[Route("[controller]")]
public class LoginRedditController : ControllerBase
{        
    [HttpGet]
    public ActionResult<string> Get(string longUrl)
    {
        Console.WriteLine(longUrl);
        return "OK";
    }
}

The longUrl string value is automatically taken from the query arguments passed to the route. And the route for the action is combined from that [Route] attribute on the controller and the [HttpGet] attribute on the action.

Upvotes: 1

mj1313
mj1313

Reputation: 8459

The Route Attribute specified the format of the url. You missed the "api" part in your url, and it should be like this:

http://localhost:5001/api/LoginReddit?longUrl=https://www.reddit.com/r/playmygame/comments/glftsj/stickn_roll_collect_everything_as_you_roll/

[ApiController]
[Route("api/[controller]")]
public class LoginRedditController : ControllerBase
{        
    [HttpGet]
    public ActionResult<string> Get([FromQuery]string url)
    {
       Console.WriteLine(longUrl);
       return "OK";
    }
}

Upvotes: 0

Related Questions