如何将多个参数传递给MVC 6控制器中的Get方法.例如,我希望能够拥有如下内容.
[Route("api/[controller]")]
public class PersonController : Controller
{
public string Get(int id)
{
}
public string Get(string firstName, string lastName)
{
}
public string Get(string firstName, string lastName, string address)
{
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以查询一下.
api/person?id=1
api/person?firstName=john&lastName=doe
api/person?firstName=john&lastName=doe&address=streetA
Run Code Online (Sandbox Code Playgroud) 我注意到有很多关于这个主题的类似问题。
调用以下任何方法时出现此错误。
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException:请求匹配多个终结点。
但是,我无法弄清楚解决问题的最佳做法是什么。到目前为止,我还没有设置任何特定的路由中间件。
// api/menus/{menuId}/menuitems
[HttpGet("{menuId}/menuitems")]
public IActionResult GetAllMenuItemsByMenuId(int menuId)
{
....
}
// api/menus/{menuId}/menuitems?userId={userId}
[HttpGet("{menuId}/menuitems")]
public IActionResult GetMenuItemsByMenuAndUser(int menuId, int userId)
{
...
}
Run Code Online (Sandbox Code Playgroud) 我正在使用mvc 6创建一个web api.现在我正在尝试从我的数据库中获取一个元素.此表中的键是一个字符串(电子邮件地址).我无法访问此数据库,因此我无法更改此表的密钥.
现在,当创建一个演示webapi时,我能够创建一个控制器来根据一个int键提取项目.但是当尝试通过字符串获取元素时,程序崩溃了.
[Route("api/[controller]")]
public class TodoController : Controller
{
[HttpGet("{id:string}", Name = "GetByIdRoute")]
public IActionResult GetById (string id)
{
var item = _items.FirstOrDefault(x => x.Id == id);
if (item == null)
{
return HttpNotFound();
}
return new ObjectResult(item);
}
}
Run Code Online (Sandbox Code Playgroud)
当试图访问此路径(example.com/api/Todo/key)时键是字符串我在startup.cs中得到异常
浏览器中的异常如下:
System.InvalidOperationException路径'api/Todo/{id:string}'上的约束条目'id' - 'string'无法通过类型'DefaultInlineConstraintResolver'的约束解析器解析.
代码中断的startup.cs的一部分是:
// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
Run Code Online (Sandbox Code Playgroud)
我似乎无法弄清楚为什么我不允许通过一个字符串键获得一个项目.这是否可能,如果是这样,我做错了什么?
我正在使用ASP.NET Core MVC创建一个网站.当我点击某个动作时,我收到此错误:
AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:
Web.Controllers.ChangeEventsController.Create (Web)
Web.Controllers.ProductsController.CreateChangeEvent (Web)
Run Code Online (Sandbox Code Playgroud)
这就是我在我的ProductsController的index.cshtmlm中定义我的动作的方法:
<a asp-controller="ChangeEvents" asp-action="Create" asp-route-id="@item.Id">Create Change Event</a>
Run Code Online (Sandbox Code Playgroud)
这是我的路线:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)
以下是我定义操作的方式:
// ChangeEventsController
[HttpGet("{id}")]
public IActionResult Create(Guid id)
// ProductsController
[HttpGet("{id}")]
public IActionResult CreateChangeEvent(Guid id)
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
更新
感谢@MegaTron的回复,但是我想知道为什么我不能为不同的控制器提供相同的操作路径.如果我有许多控制器,每个创建实体,我觉得你提出的解决方案不会很好地扩展.
所以,我正在使用Web API(ASP.NET Core 2)并遇到路由问题.
我有几个控制器,如:
SchoolController
TeacherController.
两者都有获取: Get(int id)
问题是当我运行它时,我甚至在实际能够调用方法之前就会遇到运行时错误.
Attribute routes with the same name 'Get' must have the same template:
Action: MyProject.WebAPI.Controllers.SchoolController.Get (MyProject.WebAPI)' - Template: 'api/school/{id}'
Action: MyProject.WebAPI.Controllers.TeacherController.Get (MyProject.WebAPI)' - Template: 'api/teacher/{id}'
Run Code Online (Sandbox Code Playgroud)
当控制器应该拥有自己的Get等时,为什么会这样做...所以你可以这样做:
/api/{controller}/1
etc... ?
Run Code Online (Sandbox Code Playgroud)
现在,我还有另一个Get方法,它们都在它们的控制器中但具有不同的方法签名以及不同的HttpGet名称,即:
// TeachersController:
[Produces("application/json")]
[Route("api/teacher")]
public class TeacherController : Controller
{
// GET: api/Teacher/5
[HttpGet("{id}", Name = "Get")]
public IActionResult Get(int id)
{
// BLAH
}
}
Run Code Online (Sandbox Code Playgroud)
并为学校控制员:
[Produces("application/json")]
[Route("api/school")]
public class SchoolController : Controller
{
[HttpGet("{id}", Name = "Get")]
public …Run Code Online (Sandbox Code Playgroud) c# .net-core asp.net-core asp.net-core-webapi asp.net-core-routing
我试图支持每个控制器的多个Get()方法,以及只能通过web api访问的特殊命名方法.我已经在MVC 5中完成了这个,但似乎无法弄清楚它是如何在MVC 6中完成的.任何想法?谢谢.
我在Asp.net核心中阅读了很多关于API的路径的主题,但我无法使其工作.
首先,这是我的控制器:
Public class BXLogsController : Controller
{
//[HttpGet("api/[controller]/ID/{id}", Name = "GetL")]
public IActionResult GetById(string id)
{
if (id.Trim() == "")
return BadRequest();
else
{
Logs l = AccessBase.AccBase.GetLog(id);
return Json(l);
}
}
//[HttpGet("api/[controller]/API/{apiname}", Name = "GetLAPI")]
public IActionResult GetByAPI(string apiname)
{
if (apiname.Trim() == "")
return BadRequest();
else
{
List<Logs> lstLogs = AccessBase.AccBase.GetLogsApi(apiname);
return Json(lstLogs);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用HttpGetAttribute带路径(请参阅注释),但这不起作用.
所以我想使用MapRoute方法,但这也不起作用.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "LogsId",
template: "api/[controller]/ID/{id}",
defaults: new { controller = "BXLogs", action …Run Code Online (Sandbox Code Playgroud) c# .net-core asp.net-core asp.net-core-webapi asp.net-core-routing
我使用默认的ASP.NET Core MVC模板创建了一个项目.我想在下面创建一个RESTful API /api/{Controller}.我添加了一个新的Web API控制器(标准Web API控制器类模板),但我无法调用它.我收到一条错误消息,指出无法找到该页面.我尝试在Startup.cs中添加一个路由,但它没有做任何事情:
app.UseMvc(routes =>
{
routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(name: "api", template: "api/{controller=Admin}");
});
Run Code Online (Sandbox Code Playgroud)
编辑:
就像我说的,这都是默认模板.这是我添加的Web API控制器:
[Route("api/[controller]")]
public class AdminController : Controller
{
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
Run Code Online (Sandbox Code Playgroud) c# asp.net-core-mvc asp.net-core asp.net-core-webapi asp.net-core-routing
在.NET Core MVC中使用嵌套路由时寻找最佳实践.
假设CampusController.cs使用基本模型:
[Route("api/campus/")]
public class CampusController : Controller
{
...
[HttpGet]
[Route("{campusId}")]
public IActionResult GetCampusInfo ([FromQuery]int campusId) { ... }
}
Run Code Online (Sandbox Code Playgroud)
并BuildingController.cs与儿童模型一起使用:
[Route("api/campus/{campusId}/building")]
public class BuildingController : Controller
{
...
[HttpGet]
[Route("{buildingId}")]
public IActionResult GetBuilding ([FromQuery]int buildingId) { ... }
[Route("{buildingId}/")]
public IActionResult GetBuilding ([FromQuery]int buildingId) { ... }
....
(more Action Methods)
}
Run Code Online (Sandbox Code Playgroud)
如果buildingId直接映射到数据库,即使提供campusId的不是父级,也可以检索它.为了在调用时保持URL清洁,/api/campus/{campusId}/building/{buildingId}我想验证{campusId}并返回4xx编码的IActionResult,如果它无效的话.必须有一种比在每个Action Method里面包含验证逻辑更好的方法BuildingController.
CampusController首先调用验证方法,然后调用方法BuildingController?campusId如果验证失败,有没有办法让控制器级验证可以短路并返回ActionResult?编辑:当我提到验证逻辑时,我指的是API信号; …
我有一个通用控制器,它有几个派生的控制器类.但我无法弄清楚如何处理HttpGet的路由名称,因为它需要不变.
[HttpGet("{id}", Name ="should not hard coded here for derived class")]
public virtual async Task<IActionResult> Get(int id)
Run Code Online (Sandbox Code Playgroud)
我需要路由名称,因为在我的HttpPost函数中我想返回需要HttpGet的路由名称的 CreatedAtRoute()
路由名称不能进行硬编码,因为所有派生类都需要具有不同的路由名称.
这是基本控制器
public abstract class BaseController<TEntity, TContext> : Controller where TEntity : BaseOptionType, new() where TContext : DbContext
{
private readonly IGenericRepository<TEntity, TContext> _repository;
private readonly ILogger<BaseGenericOptionTypesController<TEntity, TContext>> _logger;
public BaseController(IGenericRepository<TEntity, TContext> repository, ILogger<BaseController<TEntity, TContext>> logger)
{
_repository = repository;
_logger = logger;
}
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{id}", Name = "should not hard code here for derived class")]
public …Run Code Online (Sandbox Code Playgroud) c# asp.net-core-mvc asp.net-core-webapi asp.net-core-routing