英文:
How to correctly convert a MVC controller to an API controller
问题
以下是将ASP.NET Core MVC控制器转换为API控制器的最佳方式,以处理MVC特定功能(如ModelState
,Redirect
,RedirectToAction
,ViewData
):
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginUserDto loginUserDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var rs = await _accountService.SignInAsync(loginUserDto);
if (rs.Succeeded)
{
// 在这里处理成功登录的逻辑
return Ok(new { message = "Welcome back!" });
}
else if (rs.Data.RequiresTwoFactor)
{
// 处理需要两步验证的逻辑
return Ok(new { message = "Two-step verification required" });
}
else if (rs.Data.IsLockedOut)
{
// 处理账户被锁定的逻辑
return Ok(new { message = "Account locked" });
}
else
{
// 处理无效登录尝试的逻辑
return BadRequest(new { message = "Invalid Login Attempt" });
}
}
请注意,API控制器通常不会使用Redirect
或ViewData
等MVC特定功能。相反,它们通常会返回适当的HTTP响应,例如Ok
表示成功,BadRequest
表示错误。根据API的需要,你可以在这里处理成功和失败的逻辑,并返回相应的响应消息。
英文:
The following controller is developed by ASP.NET Core MVC. I plan to convert it into an API controller. What is the best way to convert MVC-specific features (such as ModelState
, Redirect
, RedirectToAction
, ViewData
) to API ones?
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginUserDto loginUserDto, string returnUrl)
{
if (!ModelState.IsValid) return View(loginUserDto);
var rs = await _accountService.SignInAsync(loginUserDto);
if (rs.Succeeded)
{
TempData["notification"] = "<script>swal(`" + "Welcome Back!" + "`, `" + "Hello " + loginUserDto.UserName + ", Welcome back!" + "`,`" + "success" + "`)" + "</script>";
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
else if (rs.Data.RequiresTwoFactor)
{
var sendCode = true;
return RedirectToAction("LoginTwoStep", new { loginUserDto.UserName, loginUserDto.RememberMe, returnUrl, sendCode });
}
else if (rs.Data.IsLockedOut)
{
ModelState.AddModelError(string.Empty, "Account locked");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
}
ViewData["ReturnUrl"] = returnUrl;
return View(loginUserDto);
}
答案1
得分: 1
根据评论所说,在 Web API 中,您需要返回 JsonResult
而不是 view
。因此,在这里,如果 Modelstate.IsValid
为 false,您可以使用 Return BadRequest(some message)
来返回 400 错误。您的前端框架将在视图之间执行重定向。如果您想从后端返回重定向 URL 和一些数据,您可以自定义返回类型。
public class CustomResponse
{
public string redirectUrl { get; set; }
public string data { get; set; }
}
动作:
var response = new CustomResponse
{
redirectUrl = "xxxxxxxxx",
data = "some data"
};
return Ok(response);
您还可以参考以下资源:
英文:
As the comment said, You need to return JsonResult
instead of view
in Web Api, So here if Modelstate.IsValid
is false, You can use Return BadRequest(some message)
to return a 400 error. Your frontend framework will achieve redirect between views, If you want to return the redirect Url and some data from backend, you can custom return type
public class CustomResponse
{
public string redirectUrl { get; set; }
public string data { get; set; }
}
Actione
var response = new CustomResponse
{
redirectUrl = "xxxxxxxxx",
data = "somed ata"
};
return Ok(response);
You can also refer to Format response data in ASP.NET Core Web API,Controller action return types in ASP.NET Core web API.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论