请有人知道如何在asp.net Web API 2.1中跟随三个模块一起工作
我所试图做的是开发和Web API,它将会提供恒定的格式JSON数据,意味着如果实际数据
{"Id":1,"UserName":"abc","Email":"abc@xyz.com"}
Run Code Online (Sandbox Code Playgroud)
然后我喜欢把json作为
{__d:{"Id":1,"UserName":"abc","Email":"abc@xyz.com"}, code:200, somekey: "somevalue"}
Run Code Online (Sandbox Code Playgroud)
为此,我尝试使用自定义ActionFilterAttribute但我觉得(仍未确认)在代码遇到异常的情况下,这无法提供类似的格式化数据
请建议我最好的方向.
这是我的自定义属性的简短代码片段.另外建议我是自定义属性是有益的
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class ResponseNormalizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
var response = actionExecutedContext.Response;
object contentValue;
if (response.TryGetContentValue(out contentValue))
{
var nval = new { data=contentValue, status = 200 };
var newResponse = new HttpResponseMessage { Content = new ObjectContent(nval.GetType(), nval, new JsonMediaTypeFormatter()) };
newResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); …Run Code Online (Sandbox Code Playgroud) 我需要ModelState在Asp.net Core 2.1中间件中进行访问,但这仅可从访问Controller。
例如,我有ResponseFormatterMiddleware一个中间件,在这个中间件中,我需要忽略ModelState错误,并在“响应消息”中显示错误:
public class ResponseFormatterMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ResponseFormatterMiddleware> _logger;
public ResponseFormatterMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = loggerFactory?.CreateLogger<ResponseFormatterMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory));
}
public async Task Invoke(HttpContext context)
{
var originBody = context.Response.Body;
using (var responseBody = new MemoryStream())
{
context.Response.Body = responseBody;
// Process inner middlewares and return result.
await _next(context);
responseBody.Seek(0, SeekOrigin.Begin);
using (var streamReader = …Run Code Online (Sandbox Code Playgroud)