Request.Islocal Feature added to the Asp.Net Web API

Posted by Unknown
Request.Islocal feature added to the Asp.web API:

Asp.net introduced a good feature to the Asp.net webAPI. Frequently asp.net developers who are working local and remote environments used user defined methods to identify local requests and remote requests.So with Request.Islocal feature this functionality simplified

Request.isLocal in Web API

In the old HTTP model (System.Web.dll), Request.IsLocal returned true if the IP address of the request originator was localhost (or 127.0.0.1) or if the IP address of the request is the same as the server’s IP address.
While HttpRequestMessage indeed does not have IsLocal anymore, Web API will track this information in a Lazy<bool> inside the Request.Properties dictionary, under a rather vagueMS_IsLocal key.
With this information, we can now write a very simple extension method:
C#
1
2
3
4
5
6
7
8
public static class HttpRequestMessageExtensions
{
public static bool IsLocal(this HttpRequestMessage request)
{
var localFlag = request.Properties["MS_IsLocal"] as Lazy<bool>;
return localFlag != null && localFlag.Value;
}
}
This now allows you to simply call isLocal() anywhere in the Web API pipeline where the framework gives you access to the incoming request.
In an ApiController:
C#
1
2
3
4
5
6
public HttpResponseMessage Get()
{
    if (Request.IsLocal()) {
        //do stuff
    }
}
In a handler:
C#
1
2
3
4
5
6
7
8
9
10
11
public class MyHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.IsLocal())
{
//do stuff
}
return base.SendAsync(request, cancellationToken);
}
}
In a filter:
C#
1
2
3
4
5
6
7
8
9
10
11
public class MyFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.Request.IsLocal())
{
//do stuff
}
base.OnActionExecuting(actionContext);
}
}
Or even in a formatter:
C#
1
2
3
4
5
6
7
8
9
10
11
public class MyFormatter : JsonMediaTypeFormatter
{
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
if (request.IsLocal())
{
//do stuff
}
return base.GetPerRequestFormatterInstance(type, request, mediaType);
}
}
By the way – contrary to pulling this information out of HttpContext, this approach works for bothweb-host and self-host.
All in all – a very simple 2-line extension method, but quite useful for development purposes.

Labels:

Post a Comment

 
test