【问题标题】:HttpActionContext.Request does not have CreateResponse MethHttpActionContext.Request 没有 CreateResponse 方法
【发布时间】: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


    【解决方案1】:

    CreateResponse 是在System.Net.Http 命名空间中定义的扩展方法。因此,请确保您已通过添加正确的 using 指令将其纳入范围:

    using System.Net.Http;
    

    【讨论】:

    • Request.CreateResponse() 属于居住在 nuget 包 Microsoft.AspNet.WebApi.Client 中的 HttpRequestMessageExtensions
    【解决方案2】:

    支持这篇文章

    在一个项目中,经过一些合并和升级到最新的 .net 4.6,我们遇到了一个相关错误,这是发现的第一批帖子之一。

    症状:“方法 'Request.CreateResponse()' 没有重载需要 0 个参数”。

    问题:引用中缺少 System.Net.Http.Formating 导致错误

    解决方案:Request.CreateResponse() 属于居住在 nuget 包 Microsoft.AspNet.WebApi.Client 中的 HttpRequestMessageExtensions,恢复 nuget 包,如果这无助于从项目中删除 WebApi.Client(和依赖项),请将其添加回来并且将再次添加对 System.Net.Http.Formating 的引用。

    (替代解决方案:添加参考>浏览>转到“[解决方案文件夹]packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45”并选择“System.Net.Http.Formatting.dll”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 2017-11-10
      • 2017-12-27
      • 2016-06-01
      相关资源
      最近更新 更多