Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IHttpActionResult return Json object

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?

like image 250
Ajay Avatar asked Nov 27 '14 07:11

Ajay


People also ask

How do I return a JSON response in API?

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.

Can we return JSON in ActionResult?

JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Object Notation (JSON) format.

How do I return JSON in Web API net core?

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.


3 Answers

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.

like image 129
Taiseer Joudeh Avatar answered Oct 16 '22 00:10

Taiseer Joudeh


Try that:

[AllowAnonymous]
[HttpPost]
[Route("resetpassword")]
public IHttpActionResult ResetPassword(string email)
{
    //...
    return Json(newPassword);
}
like image 43
Sergejs Avatar answered Oct 16 '22 00:10

Sergejs


You are actually already using the key thing...

[HttpGet]
public IHttpActionResult Test()
{
     return Ok(new {Password = "1234"});
}
like image 27
user3682091 Avatar answered Oct 16 '22 00:10

user3682091