分离过滤器
This commit is contained in:
33
NX.ERP.WebAPi/Filters/ApiResultAttribute.cs
Normal file
33
NX.ERP.WebAPi/Filters/ApiResultAttribute.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Web;
|
||||
using System.Web.Http;
|
||||
using System.Web.Http.Filters;
|
||||
|
||||
namespace NX.ERP.WebAPi.Filters
|
||||
{
|
||||
public class ApiResultAttribute : System.Web.Http.Filters.ActionFilterAttribute
|
||||
{
|
||||
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
|
||||
{
|
||||
base.OnActionExecuted(actionExecutedContext);
|
||||
if (actionExecutedContext.Exception == null)
|
||||
{
|
||||
ResultModel<object> result = new ResultModel<object>();
|
||||
// 取得由 API 返回的状态代码
|
||||
result.ErrCode = 0;
|
||||
// 取得由 API 返回的资料
|
||||
result.Data = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;
|
||||
|
||||
//请求是否成功
|
||||
//result.IsSuccess = actionExecutedContext.ActionContext.Response.IsSuccessStatusCode;
|
||||
//结果转为自定义消息格式
|
||||
actionExecutedContext.Response.Content = new ObjectContent<ResultModel<object>>(result, GlobalConfiguration.Configuration.Formatters.JsonFormatter);
|
||||
// 重新封装回传格式
|
||||
// actionExecutedContext.Response = httpResponseMessage;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
29
NX.ERP.WebAPi/Filters/ExceptionFilter.cs
Normal file
29
NX.ERP.WebAPi/Filters/ExceptionFilter.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using System.Web.Http;
|
||||
using System.Web.Http.Filters;
|
||||
|
||||
namespace NX.ERP.WebAPi.Filters
|
||||
{
|
||||
public class ExceptionFilter : System.Web.Http.Filters.IExceptionFilter
|
||||
{
|
||||
public bool AllowMultiple => throw new NotImplementedException();
|
||||
|
||||
public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
|
||||
{
|
||||
var ex = actionExecutedContext.Exception;
|
||||
actionExecutedContext.Response = new System.Net.Http.HttpResponseMessage();
|
||||
|
||||
actionExecutedContext.Response.Content = new System.Net.Http.ObjectContent(typeof(ResultModel<string>),
|
||||
new ResultModel<string> { ErrCode = 500, ErrMsg = ex.Message, Data = null },
|
||||
GlobalConfiguration.Configuration.Formatters.JsonFormatter);
|
||||
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user