【问题标题】:How to post data to rest api in ASP.NET MVC?如何在 ASP.NET MVC 中将数据发布到 rest api?
【发布时间】:2022-01-25 00:02:26
【问题描述】:

我是 ASP.NET MVC 的新手,这是我的第一个项目,登录时我使用的是 SSO,我发现很难发布数据以从 rest api 获得回报。在迁移到 ASP.NET 之前,我使用 php (codeigniter) 并且运行良好,现在我想迁移到 ASP.NET。

这是我的 PHP 版本:

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);
}

我想迁移到 ASP.NET,我一直在寻找,但都失败了。

这是我的 C#/ASP.NET 代码:

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();
    }
}

请谁能帮我从 php 迁移到 ASP.NET MVC?非常感谢。

【问题讨论】:

  • 你想从控制器调用API正确吗?
  • @YasinSunni 是的,我想用正确的代码调用 API,谢谢

标签: asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

您可以使用以下代码从控制器调用 API

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);
                }
 }

【讨论】:

    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多