ASP.NET/Mono MVC4 Web API v.1应用程序.
如何捕获未定义的api方法的调用.调用http://localhost:52216/erp/api/undefinedmethod返回错误到浏览器:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http:// localhost:52216/erp/api/undefinedmethod'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'undefinedmethod'.
</MessageDetail>
</Error>
Run Code Online (Sandbox Code Playgroud)
如何捕获此错误以记录到数据库?我试过问题的代码
但仍未执行Application_Error和异常过滤器代码,错误将返回给浏览器.如何捕获此错误?
如果url没有api之类的话
'http://localhost:52216/erp/undefinedmethod'
Run Code Online (Sandbox Code Playgroud)
Application_Error正确执行.
使用VS2013 WebAPI项目模板的WebAPI配置:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Run Code Online (Sandbox Code Playgroud)
更新
我尝试改变了答案.API控制器使用表单授权,并使用标准[Authorize]属性进行修饰.如果授权失败,则标准xml api错误消息
<Error>
<Message>Authorization has been denied for this …Run Code Online (Sandbox Code Playgroud) 我在我的web api项目中有一个全局异常处理程序.这种方法很好,除非通过lambda表达式引发异常.我在下面提供了示例代码:
[HttpGet]
public IHttpActionResult Test()
{
//Throw new Exception();// this exception is handled by my ExceptionHandler
var list = new List<int>();
list.Add(1);
IEnumerable<int> result = list.Select(a => GetData(a));
return Ok(result);
}
private static int GetData(int a)
{
throw new Exception();//This is not handled by my global exception handler
}
Run Code Online (Sandbox Code Playgroud)
这是我的全局异常处理程序
public class ExceptionHandlerAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
//Do something
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的WebApiConfig类中注册它
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute( …Run Code Online (Sandbox Code Playgroud) ASP.NET/Mono MVC4 Web API v.1应用程序.
API控制器使用表单授权,并使用标准[Authorize]属性进行修饰.如果授权失败,则标准api错误消息
<Error>
<Message>Authorization has been denied for this request.</Message>
</Error>
Run Code Online (Sandbox Code Playgroud)
发生.如何通过写入日志文件来识别此错误.返回给调用者shoudl的错误消息保持不变.如何添加额外的代码,这可以写入此错误消息与整个http请求标头和正文到日志文件?
我从问题中添加了代码
从
如何在ASP.NET MVC4 Web API中捕获未定义的api方法调用
但是没有抓住错误的错误.
如何捕捉所有错误?
更新
代码需要在Windows 2003服务器中运行.我从回答中尝试了代码,但遇到了编译错误
Predefined type 'System.Runtime.CompilerServices.IAsyncStateMachine' is not defined or imported
Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference to an assembly?
Cannot find all types required by the 'async' modifier. Are you targeting the wrong framework version, or missing a reference …Run Code Online (Sandbox Code Playgroud)