How to post data to rest api in ASP.NET MVC?

Viewed 494

I am newbie to ASP.NET MVC, this is my first project, for login I'm using SSO and I find it difficult to post data to get the return from rest api. Before migrating to ASP.NET, I used php (codeigniter) and it ran well, and now I want to migrate to ASP.NET.

This is my PHP version:

public function api_sso($data) {
    $base_url = 'https://example.com/sso/login';
    $post_data="Email=".$data->email."&Password=".$data->password;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $base_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=utf-8'));   
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $result = curl_exec($ch);       

    $xml = simplexml_load_string($result,'SimpleXMLElement',LIBXML_NOCDATA);
    header('Content-Type: application/json');
    return json_decode($xml);
}

I want to migrate to ASP.NET, I have looked for, but fail all.

This is my C# / ASP.NET code:

AuthModelView.cs

public class LoginViewModel
{
        [Required(ErrorMessage = "Email is required.")]
        [Display(Name = "Email")]
        public string email { get; set; }

        [Required(ErrorMessage = "Password is required.")]
        [Display(Name = "Password")]
        //[DataType(DataType.Password)]
        public string password { get; set; }
}

AuthController.cs

[HttpPost]
public ActionResult Index(LoginViewModel smodel)
{
    try
    {
        if (ModelState.IsValid)
        {
        }

        return View();
    }
    catch
    {
        return View();
    }
}

Please can anyone help me to migrate from php to ASP.NET MVC? Thanks a lot.

1 Answers

You can call API from the controller using the below code

string uri = "https://example.com/sso/login";
using (HttpClient httpClient = new HttpClient())
{
                List<KeyValuePair<string, string>> requestParams = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("Email", smodel.email),
                    new KeyValuePair<string, string>("Password", smodel.password),
                };

                FormUrlEncodedContent requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
                HttpResponseMessage response = httpClient.PostAsync(uri, requestParamsFormUrlEncoded).Result;
                string responseStr = response.Content.ReadAsStringAsync().Result;
                if (response.StatusCode == HttpStatusCode.OK)
                {

                }
                else
                {
                    mResult.Message = "Error, StatusCode=" + response.StatusCode;
                    var errorMessage = JsonConvert.DeserializeObject<object>(responseStr);
                }
 }
Related