The best way to intercept the request and response is through MessageHandler, if you want to avoid this after the request has reached the IControllerFactory handler in the pipeline - obviously, in this case use a custom attribute
I used MessageHandlers in the past to intercept a request for api / token, create a new request and get a response, create a new response.
protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { //create a new auth request var authrequest = new HttpRequestMessage(); authrequest.RequestUri = new Uri(string.Format("{0}{1}", customBaseUriFromConfig, yourApiTokenPathFromConfig)); //copy headers from the request into the new authrequest foreach(var header in request.Headers) { authrequest.Headers.Add(header.Key, header.Value); } //add authorization header for your SPA application client and secret verification //this to avoid adding client id and secret in your SPA var authorizationHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", _clientIdFromConfig, _secretKeyFromConfig))); //copy content from original request authrequest.Content = request.Content; //add the authorization header to the client for api token var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(request.Headers.Authorization.Scheme, authorizationHeader); var response = await client.PostAsync(authrequest.RequestUri, authrequest.Content, cancellationToken); if(response.StatusCode == HttpStatusCode.OK) { response.Headers.Add("MyCustomHeader", "Value"); //modify other attributes on the response } return response; }
This works great for me. However, this handler requires the configuration file WebApiConfig.cs (RouteConfig.cs if you are using ASP.NET MVC).
Can you tell me that this does not work for you on the handler?
source share