要求と応答をインターセプトする最善の方法は、要求がパイプラインの IControllerFactory ハンドラーに到達した後にそれを回避したい場合は、MessageHandler を使用することです。その場合は明らかにカスタムの「属性」を使用します。
過去に MessageHandlers を使用して、API/トークンへのリクエストをインターセプトし、新しいリクエストを作成してレスポンスを取得し、新しいレスポンスを作成しました。
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's 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;
}
これは私にとって完璧に機能します。ただし、WebApiConfig.cs ファイル (ASP.NET MVC を使用している場合は RouteConfig.cs) に必要なこのハンドラーの構成があります。
ハンドラーで何がうまくいかないのか詳しく説明していただけますか?