【发布时间】:2019-06-19 04:01:21
【问题描述】:
我目前正在修改我的客户端应用程序以使用 Axios.js 而不是 Fetch.js HTTP 请求。在进行此切换时,我的 WebAPI 消息处理程序中似乎出现了奇怪的行为。
我有一个继承 DelegatingHandler 的自定义 APIKeyHandler。
我已经在我的应用程序启动时设置了 APIKeyHandler,因为我希望我对 API 的所有请求都通过这个 APIKeyHandler。
当我使用 Axios 库调用我的 API 端点时,请求进入 APIKeyHandler,但是当它到达调用 base.SendAsync 的行时,它不会等待响应并立即执行下一行。当我使用 Fetch、VS Code Rest Client、Postman 调用 API 时,我没有遇到这种行为。我已经比较了进入处理程序的 HttpRequestMessage,它在不同的调用者中是相同的。
我不确定在发出 Axios 请求时是否有配置设置,或者我在消息处理程序中是否做错了什么。
public class APIKeyHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isValidAPIKey = false;
IEnumerable<string> lsHeaders;
var checkApiKeyExists = request.Headers.TryGetValues("client_api_key", out lsHeaders);
if (checkApiKeyExists)
{ //check here the database for the correct combination
ApiKey clsApiKey = new ApiKey();
ApiKeyModel aModel;
aModel = clsApiKey.GetByApiKeyValue(lsHeaders.FirstOrDefault());
if (aModel.Id > 0)
{
isValidAPIKey = true;
}
else
{
isValidAPIKey = false;
}
}
//If the key is not valid, return an http status code.
if (!isValidAPIKey)
return request.CreateResponse(HttpStatusCode.NotFound);
//Allow the request to process further down the pipeline
var response = await base.SendAsync(request, cancellationToken);
//Return the response back up the chain
return response;
}
}
使用 Axios 的客户端
function AxiosTest(axiosparams) {
return axios({
method: 'get',
url: axiosparams.URL,
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json',
'client_api_key': clientApiKey
},
crossDomain: true,
responseType: 'json'
}).then(function (response) {
return response;
}).catch(function (error) {
return error;
});
}
客户端使用 Fetch
function FetchData(fetchparams) {
var options = new Object();
var myHeader = new Headers();
myHeader.append('Content-Type', 'application/json; charset=utf-8');
myHeader.append('Accept', 'application/json');
myHeader.append('client_api_key', clientApiKey);
options.method = 'get';
options.headers = myHeader;
return fetch(fetchparams.url, options)
.then(JSONResponse)
.then(function (data) {
return data;
})
.catch(function (error) {
return error;
});
}
}
从浏览器添加网络输出 Network Tab Screen Capture
【问题讨论】:
-
我觉得这特别有趣:
it does not await for the response and immediately executes the next line。那么response变量的值是多少?它不再击中控制器了? -
响应返回 404。我的控制器端点似乎根本没有被击中。现在我最近将我的 API 框架从 4.5 升级到了 4.6.1,因为另一个开发人员的类库被添加到了这个项目中。
-
您能否也使用 Fiddler 之类的工具发布这 2 个 API 客户端的请求? (或者,如果您使用的是 Chrome,请查看 F12>Network 选项卡,向我们展示这两个请求的详细信息)
-
已添加。我查看了标头、响应标头和请求标头选项卡,它们是相同的。除了 fetch 调用添加 Content-Type 标头外,Axios 调用没有它,即使我已在请求中添加它。
标签: asp.net-web-api asp.net-web-api2 axios fetch