在 ASP.NET MVC 5 中添加不带参数的属性路由
Adding an Attribute Route without parameters in ASP.NET MVC 5
我有一个 API 控制器动作定义为:
public async Task<IHttpActionResult> ChangePassword(string userId, string password)
我最初的计划是通过 AJAX 请求的 data
属性传递 userId
和 password
,而不是通过 API url.
例如:
$.ajax({
url: "/api/users/resetpassword",
data: JSON.stringify({
"userId" : userId,
"password" : password
}),
dataType: "json",
method: "POST",
success: function () {
$("#ResetPasswordModal").modal('toggle');
toastr.success("Password Reset");
},
error: function () {
$("#ResetPasswordModal").modal('toggle');
toastr.error("Password could not be reset");
}
});
但是,如果我应用属性路由 [Route("api/users/resetpassword")]
我收到错误
No action was found on the controller 'Users' that matches the request
如果我然后将属性路由替换为[Route("api/users/{userId}/resetpassword/{password}")]
,应用程序能够成功找到ChangePassword
操作。
将属性路由应用于控制器操作时,是否要求所有属性都包含在路由中?
创建一个模型来保存从客户端发送的数据
public class ChangePasswordModel {
public string userId { get; set; }
public string password { get; set; }
}
更新操作以期望请求正文中的数据
public class UsersController: ApiController {
//...
//POST api/users/resetpassword
[HttpPost]
[Route("api/users/resetpassword")]
public async Task<IHttpActionResult> ChangePassword([FromBody]ChangePasswordModel data) {
//...
}
//...
}
这假定属性路由已在 WebApiConfig
中启用。
config.MapHttpAttributeRoutes();
并基于以下客户详细信息
url: "/api/users/resetpassword",
data: JSON.stringify({
"userId" : userId,
"password" : password
}),
dataType: "json",
method: "POST",
我有一个 API 控制器动作定义为:
public async Task<IHttpActionResult> ChangePassword(string userId, string password)
我最初的计划是通过 AJAX 请求的 data
属性传递 userId
和 password
,而不是通过 API url.
例如:
$.ajax({
url: "/api/users/resetpassword",
data: JSON.stringify({
"userId" : userId,
"password" : password
}),
dataType: "json",
method: "POST",
success: function () {
$("#ResetPasswordModal").modal('toggle');
toastr.success("Password Reset");
},
error: function () {
$("#ResetPasswordModal").modal('toggle');
toastr.error("Password could not be reset");
}
});
但是,如果我应用属性路由 [Route("api/users/resetpassword")]
我收到错误
No action was found on the controller 'Users' that matches the request
如果我然后将属性路由替换为[Route("api/users/{userId}/resetpassword/{password}")]
,应用程序能够成功找到ChangePassword
操作。
将属性路由应用于控制器操作时,是否要求所有属性都包含在路由中?
创建一个模型来保存从客户端发送的数据
public class ChangePasswordModel {
public string userId { get; set; }
public string password { get; set; }
}
更新操作以期望请求正文中的数据
public class UsersController: ApiController {
//...
//POST api/users/resetpassword
[HttpPost]
[Route("api/users/resetpassword")]
public async Task<IHttpActionResult> ChangePassword([FromBody]ChangePasswordModel data) {
//...
}
//...
}
这假定属性路由已在 WebApiConfig
中启用。
config.MapHttpAttributeRoutes();
并基于以下客户详细信息
url: "/api/users/resetpassword",
data: JSON.stringify({
"userId" : userId,
"password" : password
}),
dataType: "json",
method: "POST",