[英]How to post data to rest api in ASP.NET MVC?
我是 ASP.NET MVC 的新手,这是我的第一个项目,登录时我使用 SSO,我发现很难发布数据以从 rest Z8A5DA52ED126447D359E70C05721A8 获得回报。 在迁移到 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? 非常感谢。
您可以使用以下代码从 controller 调用 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.