ASP.NET Core Webb API中的多个HttpPost方法

时间:2019-02-28 15:52:19

标签: asp.net-core asp.net-core-mvc asp.net-core-webapi

我无法掌握ASP.NET Core中的路由规则。我有以下用户身份验证操作方法的后端和前端应用程序。由于这两种操作方法在有效负载中都具有一个带有不同或附加自变量的参数。 Http客户端实际上无法导航确切的方法,因此抛出异常“错误”的异常,这是正确的,因为这两个HttpPost方法都有一个参数不同的参数。如何确保该方法根据操作触发。代码如下:-

API控制器:-

  [Route("api/[controller]")]
  public class AccountController: Controller
  {
         [HttpPost, ActionName("Login")]
         public async Task<IActionResult> UserLogin(LoginDto user)
         {
            //Code goes here
         }

        [HttpPost, ActionName("Register")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UserRegistration(RegisterDto register)
        {
             //Code goes here
        }
  }

前端API服务

   public async Task<IActionResult> GetLoginAsync(LoginDto loginUser)
   {
                var request = "/api/account";
                var content = new StringContent(JsonConvert.SerializeObject(loginUser), Encoding.UTF8, "application/json");
                try
                {
                    var result = await ExecuteWithResiliencePolicies(() => _client.PostAsync(request, content));
                    return new StatusCodeResult((int)result.StatusCode);

                }
                catch (HttpRequestException)
                {
                    return new StatusCodeResult(StatusCodes.Status503ServiceUnavailable);
                }           
     }

     public async Task<IActionResult> PostRegistrationAsync(RegisterDto registerUser)
     {
                var request = "/api/account";
                var content = new StringContent(JsonConvert.SerializeObject(registerUser), Encoding.UTF8, "application/json");
                try
                {
                    var result = await ExecuteWithResiliencePolicies(() => _client.PostAsync(request, content));
                    return new StatusCodeResult((int)result.StatusCode);

                }
                catch (HttpRequestException)
                {
                    return new StatusCodeResult(StatusCodes.Status503ServiceUnavailable);
                }
      }

Web控制器:-

     [HttpPost, ActionName("Login")]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> UserLogin(LoginDto user)
            {
                SetCorrelation();
                if (!ModelState.IsValid)
                {
                    return RedirectToAction(nameof(Login));
                }
                await _accountService.GetLoginAsync(user);              
                return RedirectToAction("Index", "Home");
            }

            [HttpPost, ActionName("Register")]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> UserRegistration(RegisterDto register)
            {
                SetCorrelation();
                if (!ModelState.IsValid)
                {
                    return RedirectToAction(nameof(Login));
                }
                await _accountService.PostRegistrationAsync(register);
                return RedirectToAction("Index", "Home");


}

网络路由:

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "WebRoute",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" },
                    constraints: new { id = "[0-9]+" });                
            });

API路由:-

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "KtsWebAPIRoute",
                    template: "{controller=Posts}/{action=GetAsync}/{id?}");

                routes.MapRoute(
                    name: "KtsAccountRoute",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Account", Action = "Login" },
                    constraints: new { id = "[0-9]+" });
            });

2 个答案:

答案 0 :(得分:0)

有两种可能的解决方案。对于每个解决方案,前端部分都应调用以下网址

"/api/account/login"
"/api/account/register"

解决方案1 ​​

您需要在HttpPost属性中指定模板ASP.NET Core路由无法从请求中获取操作名称

[Route("api/[controller]")]
public class AccountController : Controller
{
    [HttpPost("Login")]
    public async Task<IActionResult> UserLogin(LoginDto user) { /*..*/ }
}

或者您可以将模板与ActionName

结合使用
[Route("api/[controller]")]
public class AccountController : Controller
{
    [HttpPost("[action]"), ActionName("Login")]
    public async Task<IActionResult> UserLogin(LoginDto user) { /*..*/ }
}

解决方案2

更新控制器的路线以包括动作名称

[Route("api/[controller]/[action]")]
public class AccountController : Controller
{
    [HttpPost, ActionName("Login")]
    public async Task<IActionResult> UserLogin(LoginDto user) { /*..*/ }
}

解决方案3

使用Route属性进行操作

[Route("api/[controller]")]
public class AccountController : Controller
{
    [HttpPost, Route("Login")]
    public async Task<IActionResult> UserLogin(LoginDto user) { /*..*/ }
}

答案 1 :(得分:0)

使用 apiController 属性和 ControllerBase

[ApiController]
[Route("api/[controller]/[action]")]
public class AccountController : ControllerBase
{
.....
}

网址应该是这样的

var uri = "............/api/Account/Login"