刷新页面后注销

时间:2016-07-25 17:48:19

标签: javascript c# jquery asp.net ajax

我有与.NET通信的asp.net应用程序。

我的身份验证问题 - 一切正常。我登录了,但是当我刷新页面时,我会被注销。

我不完全确定这个loggin代码。你知道怎么做得更好吗?我需要针对REST API进行授权。

这是我的登录表单:

    @using (Ajax.BeginForm("LogInUser", "api/User", new AjaxOptions { HttpMethod = "GET", OnComplete = "OnLogInCompleted", LoadingElementId = "loadingImage" }))
{
    <fieldset class="login-form-box">
        <table>
            <tr>
                <td class="login-label-box">@Html.Label("Username")</td>
                <td class="login-label-box">@Html.Label("Password")</td>
                <td></td>
            </tr>
            <tr>
                <td >@Html.TextBox("username", null, new {@class = "login-inout"})</td>
                <td>@Html.Password("password", null, new {@class = "login-inout"})</td>
                <td><input type="submit" value="LogIn" /></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td>@Ajax.ActionLink("Register", "MainBodyContentPartial",
                                new AjaxOptions() { UpdateTargetId = "contentBox", InsertionMode = InsertionMode.Replace, 
                                                    HttpMethod = "GET", OnComplete = "OnContentChanged" })</td>
            </tr>
        </table>
    </fieldset>
}

这里是APIController,由这个Ajax.Form调用:

 [HttpGet]
    [Route("LogInUser")]
    [System.Web.Mvc.RequireHttps]
    public User LogInUser(string username, string password)
    {
        if(username == null || password == null)
        {
            return null;
        }
        string hashedPassword = GetHashString(password);
        var selectedUser = DatabaseService.Inst.GetUserByUsernameAndPassword(username, hashedPassword);
        if(selectedUser == null)
        {
            return null;
        }

        FormsAuthentication.SetAuthCookie(username, true);
        if (!Roles.IsUserInRole(selectedUser.Role))
        {
            var userRoles = Roles.GetRolesForUser(selectedUser.Username);
            if (userRoles != null && userRoles.Any())
            {
                Roles.RemoveUserFromRoles(selectedUser.Username, userRoles);
            }
            Roles.AddUserToRole(selectedUser.Username, selectedUser.Role);
        }

        selectedUser.Password = "";
        return selectedUser;
    }

,这是授权完成时调用的javascript代码:

function OnLogInCompleted(result) {
displayWaiting();
var loggedUser = result.responseJSON;
if (!loggedUser) {
    DisplayStatusMessage("Login failed.");
    return;
}
DisplayStatusMessage("You are logged in as " + loggedUser.Username);

$('#MainLoginFormBox').load(url + '/Content/LoggedUserContentPartial');
$('#navigationMenu').load(url + '/Content/UserMenuContentPartial');
$('#contentBox').load(url + '/Content/UserHomeContentPartial');
OnContentChanged();
hideWaiting();
return;

}

0 个答案:

没有答案
相关问题