(エッセンス)2020年6月29日C#クラスライブラリBaseActionFilterAsync(Filterベース)
15866 ワード
using Coldairarrow.Util;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Threading.Tasks;
namespace Core.Api
{
public abstract class BaseActionFilterAsync : Attribute, IAsyncActionFilter
{
public async virtual Task OnActionExecuting(ActionExecutingContext context)
{
await Task.CompletedTask;
}
public async virtual Task OnActionExecuted(ActionExecutedContext context)
{
await Task.CompletedTask;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
await OnActionExecuting(context);
if (context.Result == null)
{
var nextContext = await next();
await OnActionExecuted(nextContext);
}
}
///
/// JSON
///
/// json
///
public ContentResult JsonContent(string json)
{
return new ContentResult { Content = json, StatusCode = 200, ContentType = "application/json; charset=utf-8" };
}
///
///
///
///
public ContentResult Success()
{
AjaxResult res = new AjaxResult
{
Success = true,
Msg = " !"
};
return JsonContent(res.ToJson());
}
///
///
///
///
///
public ContentResult Success(string msg)
{
AjaxResult res = new AjaxResult
{
Success = true,
Msg = msg
};
return JsonContent(res.ToJson());
}
///
///
///
///
///
public ContentResult Success<T>(T data)
{
AjaxResult<T> res = new AjaxResult<T>
{
Success = true,
Msg = " !",
Data = data
};
return JsonContent(res.ToJson());
}
///
///
///
///
public ContentResult Error()
{
AjaxResult res = new AjaxResult
{
Success = false,
Msg = " !"
};
return JsonContent(res.ToJson());
}
///
///
///
///
///
public ContentResult Error(string msg)
{
AjaxResult res = new AjaxResult
{
Success = false,
Msg = msg,
};
return JsonContent(res.ToJson());
}
///
///
///
///
///
///
public ContentResult Error(string msg, int errorCode)
{
AjaxResult res = new AjaxResult
{
Success = false,
Msg = msg,
ErrorCode = errorCode
};
return JsonContent(res.ToJson());
}
}
}