6

I'm developing an API and it has two Controllers: PicturesController and AccountController. There's a method on PicturesController that returns an image and I'd like to know how to get its URL.

On another PicturesController method, I got the URL using the code bellow:

var url = Url.RouteUrl("GetPicture", new { id = picture.Id }, Request.Scheme);

But I need to get the URL of the same method, however from another controller (AccountController).

I tried the following code, but it results null.

var url = Url.Action("GetPicture", "PicturesController", new { id = picture.Id }, Request.Scheme);

That's the method:

public class PicturesController : Controller
{
  ...

   // GET api/pictures/id
    [HttpGet("{id}", Name = "GetPicture")]
    public async Task<ActionResult> Get(Guid id)
    {
        var picture = await _context.Pictures.FirstOrDefaultAsync(p => p.IsActive() && p.Id == id);

        if (picture == null)
            return NotFound();

        return File(picture.PictureImage, "image/jpg");
    }
  ...
}
1
  • 1
    Your code says GetPicture but the action is called Get Commented Feb 3, 2019 at 18:10

1 Answer 1

4

The problem is that you are using GetPicture in this code:

var url = Url.Action("GetPicture", "PicturesController", new { id = picture.Id }, Request.Scheme);

The first parameter for Url.Action is the name of the action, which in your case is Get, so it should be

var url = Url.Action("Get", "PicturesController", new { id = picture.Id }, Request.Scheme);
Sign up to request clarification or add additional context in comments.

1 Comment

Avoid using literal strings, use nameof(GetPicture) and nameof(PicturesController) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.