我的 Login.cshtml.cs 代码文件中有以下内容:
登录.cshtml.cs
public class LoginModel : PageModel
{
public string ReturnUrl { get; set; }
public bool EnableLocalLogin { get; set; } = true;
public string Username { get; set; }
public string Password { get; set; }
private readonly IIdentityServerInteractionService _interaction;
public LoginModel(IIdentityServerInteractionService interaction)
{
_interaction = interaction;
}
public IActionResult OnGet(string returnUrl)
{
ReturnUrl = returnUrl;
return Page();
}
public IActionResult OnPost([FromBody]LoginModel model, string button)
{
// todo - implement
return Page();
}
}
如果我在返回行上有一个断点OnPost
我从页面点击登录按钮 - 断点被击中 - 但是模型为空。然而,从开发工具来看,模型中的值似乎作为表单数据发送。所以我改变了[FromBody]
to [FromForm]
.
但是,当我运行此代码并点击“登录”按钮时,出现以下异常:
InvalidOperationException:无法创建“CarWarehouse.LoginModel”类型的实例。模型绑定复杂类型不能是抽象类型或值类型,并且必须具有无参数构造函数。
UPDATE
Login.cshtml 页面:
@page
@model MyProj.Pages.LoginModel
@{
ViewData["Title"] = "Consent Required";
Layout = "_Layout";
}
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@if (Model.EnableLocalLogin)
{
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Local Login</h3>
</div>
<div class="panel-body">
<form asp-route="Login">
<input type="hidden" asp-for="ReturnUrl" />
<fieldset>
<div class="form-group">
<label asp-for="Username"></label>
<input class="form-control" placeholder="Username" asp-for="Username" autofocus>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input type="password" class="form-control" placeholder="Password" asp-for="Password" autocomplete="off">
</div>
<div class="form-group">
<button class="btn btn-primary" name="button" value="login">Login</button>
<button class="btn btn-default" name="button" value="cancel">Cancel</button>
</div>
</fieldset>
</form>
</div>
</div>
</div>
}
注意我正在使用 ID Server 4 并且只是尝试实现与此存储库类似的逻辑 -https://github.com/IdentityServer/IdentityServer4.Quickstart.UI/tree/master https://github.com/IdentityServer/IdentityServer4.Quickstart.UI/tree/master
参考ASP.NET Core 中的模型绑定:[BindProperties] 属性 https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.2#bindpropertiesattribute
在 ASP.NET Core 2.1 及更高版本中可用。可应用于控制器或PageModel
类告诉模型绑定以该类的所有公共属性为目标:
[BindProperties(SupportsGet=true)]
public class LoginModel : PageModel {
public string ReturnUrl { get; set; }
public bool EnableLocalLogin { get; set; } = true;
public string Username { get; set; }
public string Password { get; set; }
private readonly IIdentityServerInteractionService _interaction;
public LoginModel(IIdentityServerInteractionService interaction) {
_interaction = interaction;
}
public IActionResult OnGet(string returnUrl) {
ReturnUrl = returnUrl;
return Page();
}
public IActionResult OnPost(string button) {
//access properties here which should be populated from form.
// todo - implement
return Page();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)