捕捉异常:

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Web.Http.Filters;
using Rongzi.BZone.Admin.Models;
using Rongzi.BZone.Common.Util; namespace Rongzi.BZone.Admin.Functions
{
public class ApiExceptionFilterAttribute : System.Web.Http.Filters.ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotImplementedException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
}
LogHelper.Error("被系统过滤捕获的异常", context.Exception); StringBuilder sbMsg = new StringBuilder();
sbMsg.AppendFormat("ControllerName={0},ActionName={1},Msg={2},StackTrace={3}",
context.ActionContext.ControllerContext.ControllerDescriptor.ControllerName,
context.ActionContext.ActionDescriptor.ActionName,
context.Exception.Message,
context.Exception.StackTrace);
LogHelper.Exception(sbMsg.ToString()); var customerError = new ResponseContext
{
Head = new ResponseHead
{
Ret = -,
Code = ErrCode.Failure,
Msg = context.Exception.Message.ToString()
},
Content = ""
};
context.Response = context.Request.CreateResponse(HttpStatusCode.BadRequest, customerError);
}
}
}

找不到地址

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web; namespace Rongzi.BZone.Admin.Functions
{
/// <summary>
/// api返回异常状态时响应处理
/// </summary>
public class ResponseDelegatingHandler : DelegatingHandler
{
async protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.MethodNotAllowed || response.StatusCode == HttpStatusCode.NotFound)
{
var customerError = new ResponseContext
{
Head = new ResponseHead
{
Ret = -,
Code = ErrCode.Failure,
Msg = (response.StatusCode == HttpStatusCode.MethodNotAllowed) ? "请求的资源上不允许请求方法(POST或GET)" : "访问的页面不存在"
},
Content = ""
};
response = request.CreateResponse(HttpStatusCode.BadRequest, customerError);
}
return response;
}
}
}
05-02 09:40