【发布时间】:2019-04-12 07:14:04
【问题描述】:
我正在研究异常记录,我为此创建了 API,API 将异常作为参数等等。
[HttpPost]
[Route("/Log")]
public IEnumerable<string> Post([FromBody] WP2Exceptions wp2Exceptions)
{
ExceptionsModel exceptionsModel = new ExceptionsModel();
exceptionsModel = _exceptions.GetExceptionsByType(wp2Exceptions.exception.GetType().ToString());
ExceptionsLogModel exceptionLogModel = new ExceptionsLogModel();
exceptionLogModel.ExceptionID = exceptionsModel.ExceptionID;
exceptionLogModel.ModuleName = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;
exceptionLogModel.ExceptionMessage = wp2Exceptions.exception.Message;
exceptionLogModel.ExceptionType = wp2Exceptions.exception.GetType().ToString();
exceptionLogModel.ExceptionSource = wp2Exceptions.exception.Source.ToString();
exceptionLogModel.ExceptionUrl = wp2Exceptions.exception.StackTrace;
_exceptionsLog.AddExceptionsLog(exceptionLogModel);
return new string[] { exceptionsModel.ExceptionType, exceptionsModel.Message };
}
public class WP2Exceptions
{
public string moduleName { get; set; }
public Exception exception { get; set; }
}
当我在参数中传递异常时,我收到“错误请求”错误
测试代码
public async void callAPI()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:50558/");
try
{
string s = null;
string sp = s.ToString();
}
catch (Exception ex)
{
var mydata = "{'exception':'" + JsonConvert.SerializeObject(ex) + "','moduleName':'WEBAPI'}";
var response = await client.PostAsync("Log", new StringContent(mydata, Encoding.UTF8, "application/json"));
if (response != null)
{
Console.WriteLine("Log ID - " + response.ToString());
}
}
}
请纠正我做错的地方,或者我们可以将 异常对象 作为 WEB API 参数传递吗?
【问题讨论】:
-
您可以将任何对象发送到 HTTP 端点,只要您将其序列化为 JSON 或 XML 甚至纯文本。不过,您可以创建一个具有所需属性的
mydata对象并将其序列化,而不是连接字符串。你可以使用匿名类型,例如var myData=new {exception=ex,moduleName="WebApi"}; var str=JsonConvert.SeriqalizeObject(myData); -
Bad Request如果请求实际上是错误的,则返回,例如由于不适当的标头。使用 Fiddler 或其他调试代理查看实际发送到服务器的内容。可能是连接字符串导致无效的 JSON 字符串。异常消息中的单引号或泛型类型声明足以创建无效字符串 -
@pangaiotis 不工作。还是同样的问题,等待 client.PostAsync("Log", new StringContent(JsonConvert.SerializeObject(mydata), Encoding.UTF8, "application/json"));
-
因为错误请求不是由内容引起的。这是另一个问题,例如错误的标题。您使用的字符串连接虽然增加了复杂性并允许更多错误潜入。您使用 Fiddler 吗?请求是什么样的?序列化的异常是什么样的?是不是太大了?你能发布一个不同的对象吗?
标签: c# asp.net-web-api2 asp.net-core-webapi