1

I'm using asp.net core with mvc, In my application there is an account controller with register and login actions like as below.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(LoginViewModel loginViewModel)

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel loginViewModel)

I want to login the user on a successful registration without duplicating the login code in the register action, so in short, How do I redirect the register post to the login post with the LoginViewModel on submitted?

Is it possible to simply call the login action directly from the register action ?

I'm using the same object for the sake of simplicity/compatibility.

Dipak Delvadiya
  • 2,112
  • 2
  • 19
  • 33
mynameisjeff
  • 213
  • 3
  • 11
  • please check https://stackoverflow.com/questions/16643414/asp-net-mvc-redirecttoaction-with-parameters-to-post-action – Jayakrishnan May 25 '17 at 05:19
  • @JayakrishnanGounder that works but i'm still worried that this will result into unknown behaviour or future bugs, but ill add the answer for the lack of a better one – mynameisjeff May 25 '17 at 05:24
  • Instead of calling another post Actionresult, you can separate the code for login and declare it as a method and call that method from registration and login controller.Hope it helps. Otherwise i will post some code snippets – Jayakrishnan May 25 '17 at 05:26
  • that will work too, but same concept, ill end up returning another function's task result instead of the action that was called, i still dunno if that will do any conflicts but yeah still a valid helpful option, thanks anyway – mynameisjeff May 25 '17 at 05:44

1 Answers1

0

for the lack of a better answer, ill just post this till someone come up with a better answer from ASP.NET MVC: RedirectToAction with parameters to POST Action

simply call the POST action you wish to redirect to from the method you're in like

return Login(loginViewModel).Result; //for async methods
return Login(loginViewModel); //for sync methods

disclaimer: i've no idea if that's the absolute right way to do it, or if it is going to introduce any bugs later, but it works for now

mynameisjeff
  • 213
  • 3
  • 11
  • This seems like a weaker solution. Re-POSTing is an extra HTTP round trip, which makes your server do more work and your site seem slower. You should abstract the login code in your existing method to a place that can be called from your existing Login() and Register() functions, and avoid that extra POST. – Joel Coehoorn May 25 '17 at 18:32