3

我正在开发一个 ASP.Net Web API 应用程序,并且我使用 AuthorizeAttribute 进行身份验证。当认证失败时,执行的代码就是这个。

protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
        return;
    }

此代码导致从浏览器显示未经授权的请求页面,但我想要的是显示我设计的自定义页面。我怎么做?

4

2 回答 2

6

看看这个:http ://weblogs.asp.net/jgalloway/archive/2012/03/23/asp-net-web-api-screencast-series-part-6-authorization.aspx

它基本上说的是,您必须检查客户端的结果代码,如果是 401(未经授权),请将用户重定向到您设计的自定义页面:

$(function () { 
    $("#getCommentsFormsAuth").click(function () { 
        viewModel.comments([]); 
        $.ajax({ url: "/api/comments", 
           accepts: "application/json", 
           cache: false, 
           statusCode: { 
            200: function(data) { 
                viewModel.comments(data); 
            }, 
            401: function(jqXHR, textStatus, errorThrown) { 
                self.location = '/Account/Login/'; 
            } 
        } 
    }); 
  }); 
});
于 2012-09-19T17:05:28.770 回答
4

如果您使用 WebApi,我认为您不能从 HandleUnathorizedRequest 中重定向到您的自定义页面。代码结果显示未经授权的请求页面,因为这是您的浏览器响应 403 代码的方式。WebApi 适用于 HttpMessage 交换,默认使用 Json 或 Xml 媒体类型。如果您想以 text/html 形式返回您的自定义页面,那么您必须编写自己的媒体格式化程序,如下所述:http ://www.asp.net/web-api/overview/formats-and-model-binding/媒体格式化程序

于 2012-08-05T21:36:39.693 回答