Message Interceptor in Web API
Track the pipeline
process, wherein we can also validate or intercept the incoming API request.
Microsoft had given us some of classes using that we can override the API
Pipeline. In this example, I will implement DelegatingHandler
Here just creating a
class “SecurityMessageHandler” which is inherited
from “DelegatingHandler”
Class Declaration
public class SecurityMessageHandler:DelegatingHandler
{
public SecurityMessageHandler()
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IEnumerable<string>
headerValues;
var tokenHeader = string.Empty;
if (request.Headers.TryGetValues("Authorization", out
headerValues))
{
tokenHeader =
headerValues.FirstOrDefault();
}
if (!request.RequestUri.AbsolutePath.StartsWith("/api/"))
{
return await base.SendAsync(request,
cancellationToken);
}
if (string.IsNullOrWhiteSpace(tokenHeader))
{
if (request.RequestUri.AbsolutePath.Contains("api/auth/"))
{
return await base.SendAsync(request,
cancellationToken);
}
else
{
return await SendError("Wrong API Key", HttpStatusCode.Forbidden);
}
}
return await base.SendAsync(request,
cancellationToken);
}
private Task<HttpResponseMessage> SendError(string error, HttpStatusCode code)
{
var response = new HttpResponseMessage();
response.Content = new StringContent(error);
response.StatusCode = code;
return Task<HttpResponseMessage>.Factory.StartNew(()
=> response);
}
}
Register the Handler
In given file location
app_start\webapiconfig.cs
config.MessageHandlers.Add(new SecurityMessageHandler());
Now under the module “SendAsync”
We can track or validate the incoming API with
different process
if (!request.RequestUri.AbsolutePath.StartsWith("/api/"))
{
return await base.SendAsync(request,
cancellationToken);
}
Earlier we were using
base.SendAsync(request, cancellationToken).ContinueWith( (task)
=>
{
var response = task.Result;
response.Headers.Add("X-Custom-Header",
"Custom-Header.");
return response;
} );
Note: .ContinueWith from C#5 onwards, eased with
using “async”
and “await”
see in above code
Message Interceptor in Web API
Reviewed by Rupesh
on
21:50
Rating:
No comments: