问题
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:
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);
来源:https://stackoverflow.com/questions/54505817/dotnet-core-api-get-the-url-of-a-controller-method