是否可以在MVC中更改路由控制器名称?在MVC 5中,我会这样做:
[RoutePrefix("MySpecialSauce")]
public class ProductsController : Controller
{
[Route("GetBy/{id}")]
public MyObject GetBy(int id)
{
return something(id);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我所能找到的就是使用控制器的默认名称:
[Route("[controller]")]
public class ProductsController : Controller
{
[HttpGet("GetBy/{id}")]
public MyObject GetBy(int id)
{
return something(id);
}
}
Run Code Online (Sandbox Code Playgroud)
我想为我的路线使用与实际控制器名称不同的名称.你怎么做到这一点?
假设我的应用程序URL是myexample.com,myexample.com有用户john他有一个公开的个人资料链接john.myexample.com如何处理这种类型的请求,在ASP.NET核心应用,并映射到UserController具有动作Profile需要username作为一个参数和returns约翰轮廓.
routes.MapRoute(
name: "user_profile",
template: "{controller=User}/{action=Profile}/{username}");
Run Code Online (Sandbox Code Playgroud) 我有一种情况,我想使用页面特定的控制器.在那个控制器中,我有一个动作方法和一堆辅助方法.在现实生活中,辅助方法是从a继承的,BaseController但为了简单起见,假设我只是在我的控制器类中直接有一个辅助方法,如下所示:
[Route("/dev/test")]
public class TestController : Controller {
public IActionResult Get() {
return UnprocessedEntityResult();
}
//Some helper method that I don't want to be considered an
//action method by the routing engine.
public IActionResult UnprocessedEntityResult() {
return StatusCode(StatusCodes.Status422UnprocessableEntity);
}
}
Run Code Online (Sandbox Code Playgroud)
我特别想使用基于属性的路由,我希望在类级别指定基于属性的路由.
鉴于上面编码的情况,AmbiguousActionException当/dev/test访问路由时将抛出a 并且它将指示该情况
AmbiguousActionException:匹配多个动作.以下操作匹配路由数据并满足所有约束:
App.Dev.TestController.Get
App.Dev.TestController.UnprocessedEntityResult
如何告诉路由引擎UnprocessedEntityResult()不是动作方法?我假设必须有一些属性,我可以应用于该方法,但我一直无法找到它.
如果控制器中存在某些操作,我正在寻找一种覆盖操作调用的方法。
想象 :
[Route("api/[controller]")]
public partial class UsersController : BaseController {
[HttpGet("Friends/{id}")]
public IActionResult GetFriends(int id) {
// some code
}
Run Code Online (Sandbox Code Playgroud)
然后我在另一个文件中:
[Route("api/[controller]")]
public partial class UsersController : BaseController {
[HttpGet("Friends_custom/{id}")]
public IActionResult GetFriends_custom(int id) {
// some code
}
Run Code Online (Sandbox Code Playgroud)
我希望我的前端只调用
/users/friends
Run Code Online (Sandbox Code Playgroud)
如果 _custom 存在,我怎样才能获得匹配 _custom 的 asp 路由?
ASP.NET Core 2.2引入了一个使用参数转换器对路径URL进行分段的选项,如下所示:
routes.MapRoute(
name: "default",
template: "{controller=Home:slugify}/{action=Index:slugify}/{id?}");
Run Code Online (Sandbox Code Playgroud)
我做了如下相同的事情:
routes.MapRoute(
name: "default",
template: "{controller:slugify}/{action:slugify}/{id?}",
defaults: new { controller = "Home", action = "Index" });
Run Code Online (Sandbox Code Playgroud)
我的路由配置ConfigureServices方法如下:
services.AddRouting(option =>
{
option.LowercaseUrls = true;
});
Run Code Online (Sandbox Code Playgroud)
但出现以下错误:
InvalidOperationException:约束引用'slugify'无法解析为类型。向“ Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap”注册约束类型。
和
RouteCreationException:创建名称为“默认”且模板为“ {controller:slugify} / {action:slugify} / {id?}”的路由时发生错误。
可能是我错过了更多!请帮忙!
我正在尝试更新表中的条目game。但是,我在 ASP.NET 中的 PUT 请求似乎永远不会触发,我不知道为什么。
这是 ASP.NET 中的控制器:
[Route("game/{update.GameID}")]
[HttpPut]
public IActionResult updateGame([FromBody]Game update)
{
var result = context.Games.SingleOrDefault(g => g.GameID == update.GameID);
if (result != null)
{
result = update;
context.SaveChanges();
}
return Created("", result);
}
Run Code Online (Sandbox Code Playgroud)
这是我在 Angular 中使用的代码:
url:string;
constructor(private _http: HttpClient) {
this.url = "https://localhost:44359/api/v1/"
};
putGame(id:number, game:Game){
return this._http.put(this.url + "game/" + id, game);
}
Run Code Online (Sandbox Code Playgroud)
编辑 1:我确实有一个 GET 请求列表,它们都可以正常工作。只有 PUT 请求失败了。
在 Asp.net WebApi2 中
当调用 api/values/9b858599-7639-45da-acd6-a1323fb019b5 时,调用 get Action。
带有可选参数的操作。
当调用 api/values/9b858599-7639-45da-acd6-a1323fb019b5?maxRecords=100 或 api/values/?maxRecords=100 GetProducts Action 时。
在 Asp.net Core 中
但是在 asp.net 核心中,当 api/values/9b858599-7639-45da-acd6-a1323fb019b5 被调用时 GetProducts 动作被调用。我想在不更改现有 url 的情况下调用 Get 操作。
如何在 Asp.net core 2.0 中解决此问题
控制器
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
//https://localhost:44323/api/values/9b858599-7639-45da-acd6-a1323fb019b5
[HttpGet("{productId:Guid}", Order = 1)]
public ActionResult<string> Get(Guid productId)
{
return "value1";
}
//https://localhost:44323/api/values/9b858599-7639-45da-acd6-a1323fb019b5?maxRecords=100
//https://localhost:44323/api/values/?maxRecords=100
[HttpGet("{startRecordId:Guid?}")]
public ActionResult<IEnumerable<string>> GetProducts(Guid? startRecordId, int maxRecords, DateTimeOffset? minimumChangeDate = null)
{
return new string[] { "value1", "value2" }; …Run Code Online (Sandbox Code Playgroud) 所以我的API中有一个GebruikerController.Gebruiker是用户的荷兰人,这个控制器的作用是它记录用户,获取用户列表,添加用户并获得特定用户.但是当我为简单的登录功能引入自己的自定义post方法时,我遇到了一个问题.每当我从PostMan向函数发送一些数据时,我得到以下响应:
{"id":["值'login'无效."]}
我用这个网址访问它:
这是我的控制器:
[Produces("application/json")]
[Route("api/Gebruikers")]
public class GebruikersController : Controller
{
private readonly flowerpowerContext _context;
public GebruikersController(flowerpowerContext context)
{
_context = context;
}
// GET: api/Gebruikers
[HttpGet]
public IEnumerable<Gebruiker> GetGebruiker()
{
return _context.Gebruiker;
}
// GET: api/Gebruikers/5
[HttpGet("{id}")]
public async Task<IActionResult> GetGebruiker([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var gebruiker = await _context.Gebruiker.SingleOrDefaultAsync(m => m.Id == id);
if (gebruiker == null)
{
return NotFound();
}
return Ok(gebruiker);
}
[Route("api/gebruikers/login")]
[HttpPost]
public async Task<IActionResult> PostLogin([FromBody] …Run Code Online (Sandbox Code Playgroud) Startup.cs,锅炉板:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)
我有一个控制器类,MembersController.
[Produces("application/json")]
[Route("api/Members")]
public class MembersController : Controller
{
[HttpGet("{email},{password}")]
[Route("api/members/authenticate/")]
public async void Authenticate(String email, String password)
{
///the method that won't fire
}
// GET: api/Members/5
[HttpGet("{id}")]
public async Task<IActionResult> GetMember([FromRoute] int id)
{
///the boiler plate method that gets called
}
}
Run Code Online (Sandbox Code Playgroud)
基本上我试图添加一个方法,Authenticate我拿a username和password.我设置了一个路由和一些HTTPGet参数.但无论我多么惹它(前往http://localhost:64880/api/members/authenticate/,作为一个例子),我无法得到我添加的Authenticate方法来调用.
我想这是一个路由的事情?
我有HTTP-GET一个如下所示的方法
[Route("api/[controller]")]
[ApiController]
public class CityController : ControllerBase
{
public ActionResult Get(int id)
{
try
{
var city = new { CityName = "Gotham" };
return Ok(city);
}
catch(Exception ex)
{
return StatusCode(500);
}
}
}
Run Code Online (Sandbox Code Playgroud)
对于这两种类型的请求
要求:
GET http://localhost:49915/api/city
POST http://localhost:49915/api/city
Run Code Online (Sandbox Code Playgroud)
回复:
status: 200 OK
-------------------
{
"cityName": "Gotham"
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是,
GET,它应该接受 a 吗POST?我有一个简单的模型,因为它有 2 个字段,并且使用以下 put 方法,我想在数据库中更新它。包括删除在内的所有方法都有效,但是在 Postman 中 put 方法总是返回 405 错误。(也尝试过 WebDAV 解决方案。)我在这里错过了什么?
放置方法:
{
"MasterId":1,
"MasterName":"Test"
}
Run Code Online (Sandbox Code Playgroud)
行动
[HttpPut("{id:int}")]
public async Task<IActionResult> PutMaster(int id, Master master)
{
if (id != master.MasterId)
{
return BadRequest();
}
//...some code
return NoContent();
}
Run Code Online (Sandbox Code Playgroud)