如何更改 api return 导致 asp.net core 2.2?
How to change api return result in asp.net core 2.2?
我的要求是当 return 类型的操作为 void 或 Task 时,我想 return 我的自定义 ApiResult
代替。我尝试了中间件机制,但我观察到的响应对于 ContentLength 和 ContentType 都是空的,而我想要的是 ApiResult
空实例的 json 表示。
那我应该在哪里进行转换呢?
你只需要检查return类型,在return的基础上你就可以进行任何你想做的操作了。
这里是抽象演示:
你有一个方法:
public Action SomeActionMethod()
{
var obj = new object();
return (Action)obj;
}
现在在您的代码中,您可以使用以下代码获取方法的名称:
MethodBase b = p.GetType().GetMethods().FirstOrDefault();
var methodName = ((b as MethodInfo).ReturnType.Name);
上面代码中的p是class,里面包含了你想知道的return类型的方法。
获得方法名称后,您可以决定变量 methodName
return。
希望对您有所帮助。
.net core 中有多个过滤器,你可以试试Result filters。
对于void
或Task
,它将在OnResultExecutionAsync
中returnEmptyResult
。
尝试像
一样实现自己的 ResultFilter
public class ResponseFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
// do something before the action executes
if (context.Result is EmptyResult)
{
context.Result = new JsonResult(new ApiResult());
}
var resultContext = await next();
// do something after the action executes; resultContext.Result will be set
}
}
public class ApiResult
{
public int Code { get; set; }
public object Result { get; set; }
}
并在Startup.cs
中注册
services.AddScoped<ResponseFilter>();
services.AddMvc(c =>
{
c.Filters.Add(typeof(ResponseFilter));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
我的要求是当 return 类型的操作为 void 或 Task 时,我想 return 我的自定义 ApiResult
代替。我尝试了中间件机制,但我观察到的响应对于 ContentLength 和 ContentType 都是空的,而我想要的是 ApiResult
空实例的 json 表示。
那我应该在哪里进行转换呢?
你只需要检查return类型,在return的基础上你就可以进行任何你想做的操作了。
这里是抽象演示: 你有一个方法:
public Action SomeActionMethod()
{
var obj = new object();
return (Action)obj;
}
现在在您的代码中,您可以使用以下代码获取方法的名称:
MethodBase b = p.GetType().GetMethods().FirstOrDefault();
var methodName = ((b as MethodInfo).ReturnType.Name);
上面代码中的p是class,里面包含了你想知道的return类型的方法。
获得方法名称后,您可以决定变量 methodName
return。
希望对您有所帮助。
.net core 中有多个过滤器,你可以试试Result filters。
对于void
或Task
,它将在OnResultExecutionAsync
中returnEmptyResult
。
尝试像
一样实现自己的ResultFilter
public class ResponseFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
// do something before the action executes
if (context.Result is EmptyResult)
{
context.Result = new JsonResult(new ApiResult());
}
var resultContext = await next();
// do something after the action executes; resultContext.Result will be set
}
}
public class ApiResult
{
public int Code { get; set; }
public object Result { get; set; }
}
并在Startup.cs
services.AddScoped<ResponseFilter>();
services.AddMvc(c =>
{
c.Filters.Add(typeof(ResponseFilter));
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);