C# HttpActionContext.Request没有CreateResponse方法
我正在尝试在ASP.NETWebAPI中创建一个自定义AuthorizeAttribute来处理基本身份验证。重写HandleUnauthorizedRequest时,我发现HttpActionContext.Request没有CreateResponse方法 该项目是针对.NET4.5的MVC4。我使用nuget将Web API更新为版本2C# HttpActionContext.Request没有CreateResponse方法,c#,asp.net-mvc,asp.net-web-api,C#,Asp.net Mvc,Asp.net Web Api,我正在尝试在ASP.NETWebAPI中创建一个自定义AuthorizeAttribute来处理基本身份验证。重写HandleUnauthorizedRequest时,我发现HttpActionContext.Request没有CreateResponse方法 该项目是针对.NET4.5的MVC4。我使用nuget将Web API更新为版本2 using System; using System.Net.Http.Headers; using System.Text; using System
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 ?
}
}
}
我确信它一定是在某个地方丢失或不正确的引用,尽管它相当令人困惑。任何帮助都将不胜感激
Thank是在System.Net.Http
命名空间中定义的扩展方法。因此,请确保通过使用指令添加正确的,将其纳入范围:
using System.Net.Http;
背着这根柱子
在一个项目中,在合并并升级到最新的.NET4.6之后,我们遇到了一个相关的错误,这是最早发现的帖子之一
症状:“没有方法'Request.CreateResponse()'的重载接受0个参数”
问题:引用中缺少System.Net.Http.Formating,导致错误
解决方案:Request.CreateResponse()属于nuget软件包Microsoft.AspNet.WebApi.Client中的HttpRequestMessageExtensions,请还原nuget软件包,如果这无助于从项目中删除WebApi.Client(和依赖项),请将其添加回,并再次添加对System.Net.Http.Formating的引用
(可选解决方案:添加引用>浏览>转到“[solution folder]packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45”并选择“System.Net.Http.Formatting.dll”请求。CreateResponse()属于nuget包Microsoft.AspNet.WebApi.Client中的HttpRequestMessageExtensions