简体   繁体   English

Dotnet Core API - 获取控制器方法的 URL

[英]Dotnet Core API - Get the URL of a controller method

I'm developing an API and it has two Controllers: PicturesController and AccountController .我正在开发一个 API,它有两个控制器: PicturesControllerAccountController 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.

相关问题 Dotnet核心方法注入控制器方法 - Dotnet core method injection with controller methods Angular 6 HttpClient Post 未命中 DotNet Core 2.2 API 控制器中的 API Post 方法 - Angular 6 HttpClient Post not hitting API Post Method in DotNet Core 2.2 API Controller Angular 4 Http Post 未命中 DotNet Core 2.0 API 控制器中的 API Post 方法 - Angular 4 Http Post not hitting API Post Method in DotNet Core 2.0 API Controller 无法在 dotnet core api 上调用 controller 方法:没有中间件来处理请求 - Can't call controller method on dotnet core api: no middleware to handle the request 获取 dotnet core 中当前执行方法的名称 - Get the name of the currently executing method in dotnet core 在 dotnet core 中使用 NLog 捕获控制器名称和方法名称 - Capture controller name and method name using NLog in dotnet core 限制对dotnet Core MVC项目中的Web API 2控制器的访问 - Limit access to web api 2 controller in dotnet core mvc project 如何在dotnet核心控制器中获取表单输入的值 - How to get the value of form input in dotnet core controller 无法获取 Web API 控制器方法的 URL - Unable to get Web API controller method's URL Get url to web api controller method in the Razor Pages app? - Get url to web api controller method in the Razor Pages app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM