Dotnet Core API - Get the URL of a controller method

雨燕双飞 提交于 2021-01-27 15:01:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!