Server-side Blazor page post to Razor page http error 400

别来无恙 提交于 2020-05-16 12:31:24

问题


I am trying to post my username and password from a Blazor page (.razor) to a Razor Page(.cshtml) but I get http error 400 all the time.

LoginControl.razor

<form method="post" action="login">
        <input type="text"
               name="username"
               @bind="@Username"
               placeholder="User Name" />
        &nbsp;&nbsp;
        <input type="password"
               name="password"
               placeholder="Password"
               @bind="@Password" />&nbsp;&nbsp;&nbsp;
        <button class="ml-md-auto btn btn-primary">Loggin</button>
    </form>

Login.cshtml.cs

public async Task<IActionResult> OnPostAsync([FromServices] IUserProvider provider, string username, string password)
    {
Login stuff
}

回答1:


Bad request (400) means that the server cannot understand you

The method="post" is not applicable in Blazor or any other SPA frameworks. In Blazor there is special code that prevent a post back. Of course you can force a postback, which means that your Blazor page expires, and if you try to return to it, it is rerendered, and all your previous state is lost.

What you're trying to do here is to get the user's credentials in a Blazor component, and then try to post the data to a Razor Page Model for validation. You can't do that, and you should not do that. You should redirect your user to a login page in which he enters his credentials and those credentials should be validated against some sort of store, say SqlServer database, and then returns to the Blazor app. Remember, the redirection to a Razor Page means that your Blazor app has expired. One again you do not post the user's credentials to the Login Razor Page. The user should enter his his credentials on Login.cshtml

I'd suggest you to use the Blazor built-in system to enable authentication and authorization. This system uses the Identity Ui (Razor Pages) to authenticate the user. It does exactly what you're trying to do. See here.... Also, use the Forms Components provided by Blazor, such as EditForm, InutText, etc.



来源:https://stackoverflow.com/questions/57689443/server-side-blazor-page-post-to-razor-page-http-error-400

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!