您好我遇到了非常有趣的bug,并且无法理解为什么会发生这种情况。我通过httpclient的GetAsync方法从我的其他项目调用GetAllDocuments()方法到api。但问题是GetAllDocuments返回,然后再次调用它!在GetAllDocuments返回两次后,GetAsync返回结果。
这是调用方法:
public static async Task<Document> GetAllDocuments()
{
try
{
var response = _client.GetAsync("api/documents/GetAllDocuments").Result;
response.Content.LoadIntoBufferAsync().Wait();
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<Document>(new[] { new JsonMediaTypeFormatter() }); ;
// Return the URI of the created resource.
}
catch (Exception ex)
{
return null;
}
}
ApiController方法:
[HttpGet]
public List<Document> GetAllDocuments()
{
lock (_lock)
{
_documentsRepository = DocumentsRepository.Instance;
var result = _documentsRepository.GetDocuments();
return result;
}
}
WebConfig:
public static class WebApiConfig
{
private static HttpSelfHostServer _server;
public static void Run(string port)
{
var config = new HttpSelfHostConfiguration($"http://localhost:{port}");//"http://localhost:8080");
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute(
"newdocument", "api/documents/newdocument/{document}",new { document = RouteParameter.Optional });
config.Routes.MapHttpRoute(
"GetAllDocuments", "api/documents/GetAllDocuments/");
config.MaxReceivedMessageSize = int.MaxValue;;
config.MaxBufferSize = int.MaxValue;
_server = new HttpSelfHostServer(config);
_server.OpenAsync();
}
public static void Stop()
{
_server?.CloseAsync();
}
}