[英]Dotnet Core API - Get the URL of a controller method
I'm developing an API and it has two Controllers: PicturesController
and AccountController
.我正在开发一个 API,它有两个控制器:
PicturesController
和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:在另一个
PicturesController
方法中,我使用以下代码获取了 URL:
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
).但是我需要从另一个控制器(
AccountController
)获取相同方法的 URL。
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");
}
...
}
The problem is that you are using GetPicture
in this code:问题是您在此代码中使用了
GetPicture
:
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 Url.Action
的第一个参数是动作的名称,在你的例子中是Get
,所以它应该是
var url = Url.Action("Get", "PicturesController", new { id = picture.Id }, Request.Scheme);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.