I have created one method in mvc api
which returns string. But instead of returning string
, I want to return Json Object
. Here is my code.
[AllowAnonymous]
[HttpPost]
[Route("resetpassword")]
public IHttpActionResult ResetPassword(string email)
{
CreateUserAppService();
string newPassword =_userAppService.ResetPassword(email);
string subject = "Reset password";
string body = @"We have processed your request for password reset.<br/><br/>";
string from = ConfigurationManager.AppSettings[Common.Constants.FromEmailDisplayNameKey];
body = string.Format(body, newPassword, from);
SendEmail(email, subject, body, string.Empty);
return Ok<string>(newPassword);
}
Here it returns Ok<string>(newPassword);
Now I want to return Json object
. How can I return Json object?
To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.
JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Object Notation (JSON) format.
Run the application and navigate to the following endpoint in an API testing tool, e.g. Postman: https://localhost:44350/api/LearningResources. In this case, the Json() method returns a JsonResult object that serializes a list of Learning Resources.
You need to return it as CLR object so Web API serialize it to JSON, you can create your own POCO class or do it like this:
var passResponse = new
{
newPassword= yourNewPassword
};
But from security standpoint what you are doing is not correct, you should NEVER send plain passwords by email, you should reset user password by providing them a reset email link to your portal with some token and they should enter the new password. What you are doing here is not secure.
Try that:
[AllowAnonymous]
[HttpPost]
[Route("resetpassword")]
public IHttpActionResult ResetPassword(string email)
{
//...
return Json(newPassword);
}
You are actually already using the key thing...
[HttpGet]
public IHttpActionResult Test()
{
return Ok(new {Password = "1234"});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With