0

ログインメソッドなどを使用してAPIを作成しようとしています。ログインに問題がある場合は、カスタムHTTPエラーコードをカスタム応答本文とともにクライアントに返したいと思います。問題は、エラーが発生すると、リクエストがホームページにリダイレクトされることです。

[HttpPost]
[AllowAnonymous]
public JsonResult ApiLogIn(LoginModel model)
{
    if (ModelState.IsValid)
    {
        var outcome = _authService.LogIn(model);

        if (outcome == LogInOutcome.Success)
        {
            return Json(new { }); // Empty on success
        }
        else
        {
            Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            return Json(new { reason = outcome.ToString() });
        }
    }

    Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return Json(new { }); // Empty or invalid model
}

エラー時にリダイレクトされないようにするにはどうすればよいですか?

4

1 に答える 1

1

問題は、リクエストのライフサイクルの後半で、FormsAuthモジュールResponse.StatusCodeがが401であるかどうかを確認し、そうである場合はログインページにリダイレクトするという事実です。

別のステータスコードを試すことができます(403のように、シナリオにはあまり適切ではありません)。もう1つのオプションは、Global.asaxのイベントResponse.StatusCodeまでの設定を401に遅らせることです。EndRequest

Context.Itemsにフラグを追加し、次のフラグの存在を確認することで、これを解決しましたEndRequest

Global.asax.cs-このメソッドを追加します

protected void Application_EndRequest(Object sender, EventArgs e)
{
    if(Context.Items["AjaxPermissionDenied"] is bool) // FormsAuth module intercepts 401 response codes and does a redirect to the login page. 
    {
        Context.Response.StatusCode = 401;
        Context.Response.StatusDescription = "Permission Denied";
        Context.Response.End();
        return;
    }
}

あなたのコントローラーで

[HttpPost]
[AllowAnonymous]
public JsonResult ApiLogIn(LoginModel model)
{
    if (ModelState.IsValid)
    {
        var outcome = _authService.LogIn(model);

        if (outcome == LogInOutcome.Success)
        {
            return Json(new { }); // Empty on success
        }
        else
        {
            Context.Items["AjaxPermissionDenied"] = true;
            return Json(new { reason = outcome.ToString() });
        }
    }

    Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return Json(new { }); // Empty or invalid model
}
于 2013-01-11T14:06:00.430 に答える