ApiResponse类是我定义的返回基类,Code我定的是0成功 不等于0失败,对于Data我习惯于写object类型,不习惯写泛型,我习惯于给ControllerBase写扩展来定义我的返回方法,在写一个类继承于ControllerBase让后控制器再去继承这个类,也是可以的
对于GetUserCode和GetRoleCode是方便获取token中用户的信息
/// <summary>
/// ControllerBase扩展类
/// </summary>
public static class ControllerBaseExtensions
{
public static ActionResult<ApiResponse> Success(this ControllerBase controllerBase,object data)
{
return new ApiResponse()
{
Code = 0,
Data = data,
Msg = "成功",
Count = 0
};
}
public static ActionResult<ApiResponse> Success(this ControllerBase controllerBase, object data,int count)
{
return new ApiResponse()
{
Code = 0,
Data = data,
Msg = "成功",
Count = count
};
}
/// <summary>
/// 增改删结果
/// </summary>
/// <param name="controllerBase"></param>
/// <param name="audRes">增改删结果</param>
/// <returns></returns>
public static ActionResult<ApiResponse> Success(this ControllerBase controllerBase, bool audRes)
{
return new ApiResponse()
{
Code = audRes ? 0 : 1,
Data = audRes,
Msg = audRes ? "成功" : "失败",
};
}
public static ActionResult<ApiResponse> Success(this ControllerBase controllerBase)
{
return new ApiResponse()
{
Code = 0,
Data = true,
Msg = "成功",
Count = 0
};
}
/// <summary>
/// 失败
/// </summary>
/// <param name="controllerBase"></param>
/// <returns></returns>
public static ActionResult<ApiResponse> Failed(this ControllerBase controllerBase,string msg)
{
return new ApiResponse()
{
Code = 1,
Data = false,
Msg = msg,
Count = 0
};
}
/// <summary>
/// 从token中获取UserCode
/// </summary>
/// <param name="controllerBase"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static string GetUserCode(this ControllerBase controllerBase)
{
// 使用controllerBase.HttpContext来获取当前的HttpContext
var user = controllerBase.HttpContext.User;
var userCode= user?.FindFirstValue("UserCode");
if (string.IsNullOrEmpty(userCode)) throw new Exception("userCode为空");
return userCode;
}
/// <summary>
/// 从token中获取RoleCode
/// </summary>
/// <param name="controllerBase"></param>
/// <returns>RoleCode数组</returns>
/// <exception cref="Exception"></exception>
public static string[] GetRoleCode(this ControllerBase controllerBase)
{
// 使用controllerBase.HttpContext来获取当前的HttpContext
var user = controllerBase.HttpContext.User;
var userCode = user?.FindFirstValue("RoleCode");
if (string.IsNullOrEmpty(userCode)) throw new Exception("roleCode");
return userCode.Split(',');
}
}
标签:Core,Asp,Web,ControllerBase,return,static,new,controllerBase,public
From: https://www.cnblogs.com/cyfj/p/18049445