我有 mvc 应用程序和 webApi 应用程序。我需要通过 webApi 登录 asp.net mvc。当我使用这种方法时:
public static string GetToken(LoginModelView login)
{
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>( "grant_type", "password" ),
new KeyValuePair<string, string>( "username", login.Login ),
new KeyValuePair<string, string> ( "Password", login.Password )
};
var content = new FormUrlEncodedContent(pairs);
using (var client = new HttpClient())
{
var response =
client.PostAsync(URL + "/Token", content).Result;
var responseJson = response.Content.ReadAsStringAsync().Result;
var dictionaryToken = JsonConvert.DeserializeObject<Dictionary<string,string>>(responseJson);
string token = dictionaryToken["access_token"];
return token;
}
}
我的 mvc 不从 View 绑定(bind)模型。 行动方法
[HttpGet]
public ActionResult SignIn()
{
var login = new LoginModelView();
return View("SignIn",login);
}
[HttpPost]
public ActionResult SignIn(LoginModelView login)
{
string token = DirService.GetToken(login);
Session["token"] = token;
return RedirectToAction("success");
}
这是模型
public class LoginModelView
{
public string Login { get; set; }
public string Password { get; set; }
}
这是我的观点
@model AdminTool.Models.LoginModelView
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>LoginModelView</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Login, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Login, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Login, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Login" class="btn btn-default" />
</div>
</div>
</div>
}
当我不使用该方法时,一切正常。 相同的代码可以在另一个应用程序中运行。 有人可以帮助我吗?
最佳答案
我注意到在 LoginModelView
类中有 Login
属性,并且您在 Controller 中创建相同的对象名称 LoginModelView login
。我更改了该代码及其为我工作。
型号:-
[HttpGet]
public ActionResult SignIn()
{
var loginModelView = new LoginModelView();
return View("SignIn", loginModelView);
}
[HttpPost]
public ActionResult SignIn(LoginModelView loginModelView)
{
string token = DirService.GetToken(loginModelView);
Session["token"] = token;
return RedirectToAction("success");
}
希望它能成功!!!
祝你编码愉快!!
关于asp.net-mvc - Asp.net mvc通过httpClient连接webApi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43407688/