[英]Multiple ApiControllers for ASP.NET Core Web API
我一直試圖弄清楚如何在我的兩個 controller 文件中使用多個[Route("[Controller]")]
屬性。
從我查找的內容來看,這似乎是可能的,甚至 MS 文檔都說您可以通過創建應用了該屬性的自定義 class 或通過將其添加為Program.cs
中的程序集項來應用多個[ApiController]
屬性我也試過了。
但無論何時,當我訪問我的本地主機時,我都會收到來自 Swagger 的錯誤。 我是不是誤會了什么?
編輯:添加,如果我將Route
屬性之一更改為Route("[Action]")
它可以工作。 我不希望動作名稱與端點分開。
//LicensesController.cs
namespace Api.Controller;
using Microsoft.AspNetCore.Mvc;
using Api.Authorization;
using Api.Models;
using Api.Services;
[Authorize]
//[ApiController]
[Route("[Controller]")]
public class LicenseController : ApiController
{
private readonly LicenseServices _licenseServices;
// Parameterless constructor: because MS says so. I can't find a reason why that makes sense
public LicenseController(LicenseServices licenseServices)
{
_licenseServices = licenseServices;
}
[HttpGet]
public ActionResult<List<PartialLicense>> Licenses([FromQuery] LicenseQuery query)
{
List<PartialLicense> licenses = _licenseServices.Query(query);
if(!licenses.Any())
return NotFound();
return licenses;
}
}
// UsersController.cs
namespace Api.Controller;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Api.Authorization;
using Api.Utils;
using Api.Models.Users;
using Api.Services;
[Authorize]
//[ApiController]
[Route("[Controller]")]
public class UsersController : ApiController
{
private readonly IUserService _userService;
private readonly IMapper _mapper;
private readonly AppSettings _appSettings;
public UsersController(IUserService userService, IMapper mapper, IOptions<AppSettings> appSettings)
{
_userService = userService;
_mapper = mapper;
_appSettings = appSettings.Value;
}
[AllowAnonymous]
[HttpPost("authenticate")]
public IActionResult Authenticate(AuthenticateRequest model)
{
var response = _userService.Authenticate(model);
return Ok(response);
}
}
//ApiControllerAttribute.cs
namespace Api.Controller;
using Microsoft.AspNetCore.Mvc;
[ApiController]
public class ApiController : ControllerBase
{
}
我想通了,這是一個愚蠢的錯誤。 我沒有給[HttpGet]
屬性一個端點名稱來調用請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.