Chris
Chris

Reputation: 28064

Why is HttpRequestMessage so limited?

I'm working on my first ASP.NET Web API project and I've got a custom authorization attribute working. What I want to do is set up the attribute so that if the request is local (i.e. debugging), the authorization check is bypassed.

In all other ASP.NET MVC versions, I could check Request.IsLocal (or even Request.UserHostAddress) to see if the request was coming from the local machine, but System.Web.Http.AuthorizeAttribute only exposes the HttpRequestMessage object, which apparently has none of this information, and seems to be missing a few other things from the Request object also.

What's the deal with the whole new set of (apparently limited) classes for use with web API, and perhaps more directly, how can I get the callee's host address in my Authorize attribute?

Upvotes: 1

Views: 3073

Answers (2)

Daniel Crenna
Daniel Crenna

Reputation: 3386

I ran into this same issue when developing multiple middleware components, or supporting others who made the unfortunate, IIS-binding decision to use HttpContext, or rely on it, whether directly through HttpContext or via MS_HttpContext (which isn't an option in self-host). I wrote a small shim library to solve this problem by giving you back an HttpContext that works in both situations. You can find it on github and NuGet

Install-Package HttpContextShim

Upvotes: 0

Mark Jones
Mark Jones

Reputation: 12194

There are a couple of different examples of grabbing the request information you want here or here e.g.

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var context = actionContext.Request.Properties["MS_HttpContext"] as System.Web.HttpContextBase;
        bool isLocal = context.Request.IsLocal;

If this is truly just for debuging then it may be safer using a conditional statement like this around any debug only code - especially in a security context...

#if DEBUG 
// 
#endif 

As to why... I imagine this is at least in part to allow for easier unit testing and mocking, the HTTP Context is an ASP.NET System.Web construct... WebApi is designed to be capable as running as self hosted code independent of ASP.NET.

Upvotes: 5

Related Questions