我正在使用WebApi 2.1创建一个面向公众的API,拥有一个专用的WebApi项目(没有MVC),在自己的服务器上将IIS托管在IIS 7.5中,并且设计目标是仅返回JSON或空内容,永不返回HTML 。
我很高兴使用ExceptionFilterAttribute来处理WebApi管道中出现的异常,如下所示:
public class GlobalExceptionHandler : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
// Log the exception to Elmah
Elmah.Error error = new Elmah.Error(context.Exception, HttpContext.Current);
error.Detail = ActionState.GetRequestParameters(context) + error.Detail;
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(error);
if (context.Exception is NotImplementedException)
{
context.Response = context.Request.CreateErrorResponse(
HttpStatusCode.NotImplemented
, "The API method has not yet been implemented"
);
}
else
{
context.Response = context.Request.CreateErrorResponse(
HttpStatusCode.InternalServerError
, "A " + context.Exception.GetType().ToString() + " was thrown"
);
}
base.OnException(context);
}
}
过滤器已在App_Start中正确添加:
config.Filters.Add(new SecureVideoApiGlobalExceptionHandler());
当出现WebApi管道之外的错误时,问题就出现了。例如,请求附带了Web根目录的URI, https://mysite.com/ ,响应是403.11,HTML主体声明“Web服务器配置为不列出内容这个目录。“另一种可能性是在global.asax的Application_Start方法中调用的代码中存在错误,例如在AutoMapper代码中,该代码断言所有映射都是有效的。
我的问题是:如何在API服务器上发生任何错误时,只返回一条JSON错误消息,而不是HTML错误消息?
我试过了
<modules runAllManagedModulesForAllRequests="true">
这允许我处理global.asax中Application_Error()中的任何错误,但是我无法访问那里的Response对象以发出JSON。
答案 0 :(得分:4)
你可以做这样的属性
[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = true)]
public class ExceptionActionFilter : ExceptionFilterAttribute
{
private static Logger _log ;//= LogManager.GetLogger("mysite");
public override void OnException(HttpActionExecutedContext contex)
{
if (_log == null)
_log = LogManager.GetCurrentClassLogger();
var ex = contex.Exception;
_log.Error(ex);
contex.Response = contex.Request.CreateResponse(HttpStatusCode.OK,
new
{
ErrorMessage = contex.Exception.Message,
RealStatusCode = (int)(ex is NotImplementedException || ex is ArgumentNullException ? HttpStatusCode.NoContent : HttpStatusCode.BadRequest),
ReturnUrl = CommonContext.ErrorUrl
},
new JsonMediaTypeFormatter());
base.OnException(contex);
}
}
然后将属性放在类exc和clien方面
或使用过滤器
public class ExceptionLoggerFilter : System.Web.Http.Filters.IExceptionFilter
{
private static Logger _log;
public ExceptionLoggerFilter()
{
if (_log == null)
_log = LogManager.GetCurrentClassLogger();
}
public bool AllowMultiple { get { return true; } }
public System.Threading.Tasks.Task ExecuteExceptionFilterAsync(
System.Web.Http.Filters.HttpActionExecutedContext contex,
System.Threading.CancellationToken cancellationToken)
{
return System.Threading.Tasks.Task.Factory.StartNew(() =>
{
_log.Error(contex.Exception);
contex.Response = contex.Request.CreateResponse(HttpStatusCode.OK,
new { RealStatusCode = (int)HttpStatusCode.Forbidden, ReturnUrl = "#/error.html"},
contex.ActionContext.ControllerContext.Configuration.Formatters.JsonFormatter);
}, cancellationToken);
}
}
然后在Global.asax.cs
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
Database.SetInitializer<MySiteContext>(null);
}
和
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)//RouteCollection config)//
{
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Filters.Add(new ExceptionLoggerFilter());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
}
}
在客户端也许像是
$.controller.ajax.promise = controller.ajax.promise = function ( obj )
{
var deferred = q.defer();
$.ajax( {
type: obj.type || "GET",
url: obj.url,
context: obj.context || null,
data: obj.data || null,
contentType: obj.contentType || "application/json; charset=utf-8",
dataType: obj.dataType || "json",
success: function ( res, textStatus, jqXHR )
{
if ( res.RealStatusCode )
{
switch ( res.RealStatusCode )
{
case 400://x error
res.ClientMessage = res.ErrorMessage;
deferred.reject(res);
break;
case 408://y errors
location.href = res.ReturnUrl;
return false;
case 403://ext
msgbox.alert( {
message: 'Ma belle msg',
title: "Error"
} );
deferred.reject();
location.href = res.ReturnUrl;
return false;
default:
deferred.reject();
location.href = res.ReturnUrl;
break;
}
}
deferred.resolve( res );
return true;
},
error: function ( jqXHR, textStatus, errorThrown )
{
deferred.reject( { msg: jqXHR.statusText, jqXHR: jqXHR, textStatus:textStatus, errorThrown:errorThrown } );
}
} );
return deferred.promise;
};
我希望这有助于其他googlers在那里! (如@Thomas C. G. de Vilhena所说=)