gpt4 book ai didi

asp.net-core - 为什么我不能使用 [HttpPost] 代替 [HttpPost ("[action]")]?

转载 作者:行者123 更新时间:2023-12-02 03:49:00 28 4
gpt4 key购买 nike

我不明白为什么需要使用 [HttpPost("[action]")] 而不是 [HttpPost]

如果使用[HttpPost("[action]")],那么来自角度客户端的请求会触发 Controller 操作。

// POST: api/LeaveRequests
[HttpPost("[action]")]
public async Task<IActionResult> PostLeaveRequest([FromBody] LeaveRequest leaveRequest)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

_context.LeaveRequests.Add(leaveRequest);
await _context.SaveChangesAsync();

return CreatedAtAction("GetLeaveRequest", new { id = leaveRequest.EmployeeNo }, leaveRequest);
}

但是如果我只放置 [HttPost] 那么来自 anglular 客户端的请求不会命中 Controller 操作,而是命中路径为 [HttpGet("{id}")] 的方法

我的MVC路线

 app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");

routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});

我的角度http.post

return this.http.post(this._apiUrl, body, options)
.map(res => res.json()) // ...and calling .json() on the response to return data
.catch((error: any) => Observable.throw(error.json().error || 'Server error'))
.subscribe();

最佳答案

这个[HttpPost("blah blah")]用于定义路由link

或者,您可以使用属性路由 Read this article

[HttpPost]
[Route("PostLeaveRequest")]
public async Task<IActionResult> PostLeaveRequest([FromBody] LeaveRequest leaveRequest)
{
..................................

}

关于asp.net-core - 为什么我不能使用 [HttpPost] 代替 [HttpPost ("[action]")]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46000017/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com