【发布时间】:2014-02-19 21:37:26
【问题描述】:
我正在尝试在 ASP.Net Web API 中创建自定义 AuthorizeAttribute 来处理基本身份验证。覆盖 HandleUnauthorizedRequest 时,我发现 HttpActionContext.Request 没有 CreateResponse 方法。
该项目是针对 .net 4.5 的 MVC 4。我使用 nuget 将 Web API 更新到了第 2 版。
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Web.Http;
namespace BasicAuth.Security
{
public class BasicAuthAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
return;
}
var authHeader = actionContext.Request.Headers.Authorization;
if (authHeader != null)
{
if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(authHeader.Parameter))
{
var credentials = GetCredentials(authHeader);
//Handle authentication
return;
}
}
HandleUnauthorizedRequest(actionContext);
}
private string[] GetCredentials(AuthenticationHeaderValue authHeader)
{
var raw = authHeader.Parameter;
var encoding = Encoding.ASCII;
var credentials = encoding.GetString(Convert.FromBase64String(raw));
return credentials.Split(':');
}
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
actionContext.Response = actionContext.Request. //No CreateResponse Method ?
}
}
}
我确信它一定是某个地方的参考缺失或不正确,但它相当令人困惑。任何帮助将不胜感激。
谢谢
【问题讨论】:
标签: c# asp.net-mvc asp.net-web-api