在Web Api授权中重定向到默认值

时间:2017-12-06 15:43:16

标签: c# asp.net-web-api

我的问题:当会话过期时,用户仍然可以执行操作(搜索)。操作结果是一些垃圾(不访问控制器)。我不知道为什么;我只想将用户重定向到登录页面。

我的计划是自定义授权并覆盖HandleUnauthorizedRequest(HttpActionContext)并将用户重定向到索引。 我不知道如何重定向到我的默认页面。

示例代码:

public class SessionTimeoutAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        base.HandleUnauthorizedRequest(actionContext);
        //redirect here
    }
}

2 个答案:

答案 0 :(得分:1)

您希望将actionContext的响应设置为Unauthorized http响应。以下是如何操作的示例。

public class SessionTimeoutAttribute: AuthorizeAttribute {
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) {

        base.HandleUnauthorizedRequest(actionContext);
        actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);

    }
}

这应该有希望将用户重定向到您(希望)在CookieAuthenticationOptions中定义的页面。

编辑:说实话,如果您允许用户以与进入普通页面相同的方式访问Web API,则此类定义了Web API的用途。您应该在客户端确定来自Web api端点的响应是successunathorized等。您应该从Web api返回而不是直接redirect

如果您真的想重定向,可以尝试以下方法......

var response = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
response.Headers.Location = new Uri("https://www.stackoverflow.com");
actionContext.Response = response;

同样,我没有看到从Web API重定向的重点。它应该只返回请求的数据/错误。你应该在其他地方处理它。

答案 1 :(得分:-1)

我以为我可以直接从Web API重定向到网站......好吧,我不能。原来我不需要自定义授权,因为[授权]正确重定向。当Authorize需要时,我需要我的客户端重定向。就我而言(Angular 1,5),它是一个拦截器。

java.lang.NullPointerException: Column has no editor binding or component defined

和app.config

app.service('httpRedirectInterceptor', ['$window', function ($window) {
this.response = function (redirection) {
    if (typeof redirection.data === 'string') {
        if (redirection.data.indexOf instanceof Function &&
            redirection.data.indexOf('id="app-login-page"') != -1) {
            $window.location.pathname = "/Account/Login";
        }
    }
    return redirection;
};

this.request = function (req) {
    var elem = angular.element(document.body).find('div[ncg-request-verification-token]').attr('ncg-request-verification-token');
    req.headers['RequestVerificationToken'] = elem || "no request verification token";

    return req;
};}]);
相关问题