Reputation: 2017
I'm developing RESTful service with Microsoft ASP.NET Web API.
What I need is to have some kind of handler function, which is triggered every time when service is called, before my flow enters into controller method.
Let's say, place when I can call my database and check if provided in request header hash token has privilege to retrieve data through API, and then, if it has, continue to controller method.
Is there any programmable place like I need in WebAPI? I'm not VERY familiar with Web API data flow.
Upvotes: 2
Views: 2468
Reputation: 377
Another way would be to create your own class implementing IDispatchMessageInspector
I would add your authorization checks into afterRecieveRequest and throw an exception (http 403 probably) if they don't have the header in the request object.
Upvotes: 0
Reputation: 1038940
What I need is to have some kind of handler function, which is triggered every time when service is called, before my flow enters into controller method.
You could write a custom message handler
. For example as shown in the MSDN article:
public class ApiKeyHandler : DelegatingHandler
{
public string Key { get; set; }
public ApiKeyHandler(string key)
{
this.Key = key;
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!ValidateKey(request))
{
var response = new HttpResponseMessage(HttpStatusCode.Forbidden);
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
private bool ValidateKey(HttpRequestMessage message)
{
var query = message.RequestUri.ParseQueryString();
string key = query["key"];
return (key == Key);
}
}
Upvotes: 1