I am trying to create a custom AuthorizeAttribute in ASP.Net Web API to handle Basic Auth. When overriding HandleUnauthorizedRequest I find that the HttpActionContext.Request doesn't have a CreateResponse method.
The project is MVC 4 targetting .net 4.5. I updated Web API to version 2 using nuget.
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 ? } } }
I am sure it must be a missing or incorrect reference somewhere, it is rather confusing though. Any help would be much appreciated.
Thanks
CreateResponse
is an extension method defined in the System.Net.Http
namespace. So make sure you've brought it into scope by adding the correct using
directive:
using System.Net.Http;
Piggy backing on this post
In a project after some merging and upgrading to latest .net 4.6 we had a related error and this was one of the first posts found.
Symptom: "No overload for method 'Request.CreateResponse()' takes 0 arguments".
Problem: System.Net.Http.Formating was missing in references causing the error
Solution: Request.CreateResponse() belongs to HttpRequestMessageExtensions living in the nuget package Microsoft.AspNet.WebApi.Client, restore nuget packages and if that does not help remove WebApi.Client (and dependencies) from the project, add it back and the reference to System.Net.Http.Formating will be added again.
(alternative solution: add reference > browse > go to "[solution folder]packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45" and select "System.Net.Http.Formatting.dll"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With