本文介绍了Dotnet Core API-获取控制器方法的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 18:26