问题描述
我正在开发一个 API,它有两个控制器:PicturesController
和 AccountController
.PicturesController
上有一个返回图像的方法,我想知道如何获取它的 URL.
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.
在另一个 PicturesController
方法中,我使用下面的代码获得了 URL:
On another PicturesController
method, I got the URL using the code bellow:
var url = Url.RouteUrl("GetPicture", new { id = picture.Id }, Request.Scheme);
但是我需要从另一个控制器 (AccountController
) 获取相同方法的 URL.
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);
就是这个方法:
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");
}
...
}
推荐答案
问题是你在这段代码中使用了GetPicture
:
The problem is that you are using GetPicture
in this code:
var url = Url.Action("GetPicture", "PicturesController", new { id = picture.Id }, Request.Scheme);
Url.Action
是 action 的名称,在你的例子中是 Get
,所以它应该
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);
这篇关于Dotnet Core API - 获取控制器方法的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!