【问题标题】:Correct url for controller控制器的正确网址
【发布时间】:2019-01-17 02:51:49
【问题描述】:

您能否告诉控制器方法 GetProfileById 的正确 url 与属性 'id' 我尝试了许多 url,如 'http://localhost:5000/api/Profile/GetProfileById/1'、'http://localhost:5000/api/Profile/ProfileById/1'、'http://localhost:5000/api/ProfileById/1' 但邮递员显示消息'无法获取和我的网址'

代码如下:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SocialNetwork.Repositories;
using SocialNetwork.Repositories.GenericRepository;

namespace SocialNetwork.Controllers
{
    [Route("/api/[controller]")]
    public class ProfileController : Controller
    {
        private readonly ProfileRepository repository;

        public ProfileController(IProfileRepository repository)
        {
            this.repository = (ProfileRepository)repository;
        }

        [HttpGet("{id}")]
        [ProducesResponseType(200, Type = typeof(Profile))]
        [ProducesResponseType(404)]
        public async Task<ActionResult<Profile>> GetProfileById(int id)
        {
            var profile = await repository.GetById(id);
            if(profile != null)
            {
                return new OkObjectResult(Json(profile));
            }
            return NotFound();
        }


}

}

【问题讨论】:

  • 不会是/api/profile/&lt;ID&gt;吗?

标签: c# asp.net url asp.net-core controllers


【解决方案1】:

应该是/api/profile/&lt;id&gt;。您可以通过方法上方的[Route("/api/[controller]")] 指令来判断这一点。然后,在一个斜杠之后添加任何 id。

因此,您使用localhost(或您的域)的完整路线将是http://localhost:5000/api/Profile/1

【讨论】:

  • 为了更加精确,Route 属性与HttpGet 参数组合构成了 URL。您实际上可以拥有[HttpGet("{id}/json")],而URL 将是http://localhost:5000/api/Profile/1/json
【解决方案2】:

Routing to controller actions in ASP.NET Core”和“Routing in ASP.NET Core”是用于此目的的好文章。

在您的情况下,正确的 URL 是“http://localhost:5000/api/profile/1”。

注意:如果 Postman 仍有问题,请搜索如何配置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多