繁体   English   中英

MVC 3 API自定义响应主体出现错误

[英]MVC 3 API custom response body on error

我正在尝试使用登录方法和其他方法编写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
}

如何阻止错误重定向?

问题在于,在请求生命周期的后期,FormsAuth模块检查以查看Response.StatusCode是否为401,如果是,则重定向到登录页面。

您可以尝试使用其他状态代码(例如403,因为这不太适合您的情况)。 另一个选择是延迟将Response.StatusCode设置为401,直到Global.asax中的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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM