如何正确将MVC控制器转换为API控制器

huangapple go评论70阅读模式
英文:

How to correctly convert a MVC controller to an API controller

问题

以下是将ASP.NET Core MVC控制器转换为API控制器的最佳方式,以处理MVC特定功能(如ModelStateRedirectRedirectToActionViewData):

[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控制器通常不会使用RedirectViewData等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&lt;IActionResult&gt; Login(LoginUserDto loginUserDto, string returnUrl)
{
    if (!ModelState.IsValid) return View(loginUserDto);

    var rs = await _accountService.SignInAsync(loginUserDto);
    if (rs.Succeeded)
    {
        TempData[&quot;notification&quot;] = &quot;&lt;script&gt;swal(`&quot; + &quot;Welcome Back!&quot; + &quot;`, `&quot; + &quot;Hello &quot; + loginUserDto.UserName + &quot;, Welcome back!&quot; + &quot;`,`&quot; + &quot;success&quot; + &quot;`)&quot; + &quot;&lt;/script&gt;&quot;;
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        return RedirectToAction(&quot;Index&quot;, &quot;Home&quot;);
    }
    else if (rs.Data.RequiresTwoFactor)
    {
        var sendCode = true;
        return RedirectToAction(&quot;LoginTwoStep&quot;, new { loginUserDto.UserName, loginUserDto.RememberMe, returnUrl, sendCode });
    }
    else if (rs.Data.IsLockedOut)
    {
        ModelState.AddModelError(string.Empty, &quot;Account locked&quot;);
    }
    else
    {
        ModelState.AddModelError(string.Empty, &quot;Invalid Login Attempt&quot;);
    }

    ViewData[&quot;ReturnUrl&quot;] = 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 = &quot;xxxxxxxxx&quot;,
    data = &quot;somed ata&quot;
};
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.

huangapple
  • 本文由 发表于 2023年6月1日 01:18:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375916.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定