我有一个将错误记录到数据库中的旧日志记录 DLL。 我们希望通过 Web 调用来记录错误,而不是在我们的环境中的每个应用程序中使用 DLL。
我已经建立了一个web.api应用程序,它将错误记录到数据库中。当使用POSTMAN进行测试时,它的工作原理与广告所示。
我在演示 MVC 应用程序中添加了一个类,并连接了我的一个构造函数来执行日志命令,但调用不仅没有进入我的 web.api,而且小提琴手甚至没有显示正在进行的调用。
任何关于使其实际运行的意见将不胜感激。
这是我的代码:
在 Web.API 中调用的日志记录实用程序
public class Utilities
{
public void LogException(string exceptionMessage, string stackTrace, string appCode, string runMode, int entityId, int itmsUserID, string updateBy, string path, string method)
{
ErrorLog.Entry _error = new ErrorLog.Entry();
_error.ErrorMessage = exceptionMessage;
_error.StackTrace = stackTrace;
_error.AppCode = appCode;
_error.Path = path;
_error.Method = method;
_error.UpdateBy = updateBy;
_error.RunMode = runMode;
_error.EntityID = entityId;
//_error.Server = server; server will have to be changed to accept a setter
_error.ITMSUserID = CommonFunctions.Get_ITMSUserID(updateBy);
_error.Save();
}
}
网络接口
// POST: api/ErrorLog
public void Post([FromBody]ErrorLogEntryDTO item)
{
var utils = new Utilities();
utils.LogException(item.ErrorMessage, item.StackTrace, item.AppCode, item.RunMode, item.EntityID, item.ITMSUserID, item.UpdateBy, item.Path, item.Method);
}
MVC 控制器代码
// GET: BillingRules/Create
public virtual ActionResult CauseHandledError()
{
try
{
throw new Exception("Handled exception test");
}
catch (Exception ex)
{
var utils = new Utilities();
utils.LogException(ex, "system", MVC.BillingRules.Name, MVC.BillingRules.ActionNames.CauseHandledError);
}
return RedirectToAction(MVC.BillingRules.ActionNames.Index, MVC.BillingRules.Name);
}
MVC 应用程序中的实用程序代码
public void LogException(Exception exception, string updateBy, string path, string method)
{
try
{
var itmsUserID = CommonFunctions.Get_ITMSUserID(updateBy);
var errorDTO = new ErrorLogEntryDTO();
errorDTO.ITMSUserID = itmsUserID;
errorDTO.AppCode = _appCode.Value;
errorDTO.ErrorMessage = exception.Message;
errorDTO.StackTrace = exception.StackTrace;
errorDTO.Path = path;
errorDTO.Method = method;
errorDTO.UpdateBy = updateBy;
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:52316");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var result = client.PostAsJsonAsync("api/ErrorLog", errorDTO).Result; //ContinueWith(readTask => client.Dispose()); //
}
catch (Exception ex)
{
var myError = ex;
throw;
}
}
我很确定在这种情况下调用.Result
不会立即调用PostAsJsonAsync
方法。 因为您没有对结果执行任何操作,所以它永远不会实际执行。由于您似乎并不关心响应,因此您应该能够使用:
client.PostAsJsonAsync("api/ErrorLog", errorDTO).Wait();
我认为.Result
调用PostAsJsonAsync
调用。您正在等待响应,因此必须在此线路之后完成呼叫。无论您是否使用结果。
可以删除 [FromBody]
属性,因为默认情况下,复杂类型是从正文中读取的。
而且我无法重现您的问题。我创建了一个新的 Web API 项目和一个新的控制台项目。在 Web API 中,我已将值控制器的帖子更改为您的。在控制台项目中,我正在使用 MVC 应用程序中的LogException()
方法。它命中我的网络 api 应用程序。两者位于同一主机中还是位于不同主机中?
编辑:要使日志记录异步,您可以使用Task.Run()
即发即弃,但这取决于您拥有的应用程序。在 ASP.Net Task.Run()
中是根据 Task.Run 礼仪示例的反模式:不要在实现中使用 Task.Run。