net核心中间件中访问ModelState

net核心中间件中访问ModelState

本文介绍了在Asp.net核心中间件中访问ModelState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我需要访问Asp.net Core 2.1中间件中的 ModelState ,但这只能从 Controller 访问。

I need to access ModelState in Asp.net Core 2.1 Middleware, but this is just accessible from Controller.

例如,我有 ResponseFormatterMiddleware ,在此中间件中,我需要忽略 ModelState 错误并在响应消息中显示为错误:

For example I have ResponseFormatterMiddleware and in this Middleware I need to ignore ModelState error and show it's errors in 'Response Message':

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 = new StreamReader(responseBody))
            {
                // Get action result come from mvc pipeline
                var strActionResult = streamReader.ReadToEnd();
                var objActionResult = JsonConvert.DeserializeObject(strActionResult);
                context.Response.Body = originBody;

                // if (!ModelState.IsValid) => Get error message

                // Create uniuqe shape for all responses.
                var responseModel = new GenericResponseModel(objActionResult, (HttpStatusCode)context.Response.StatusCode, context.Items?["Message"]?.ToString());

                // Set all response code to 200 and keep actual status code inside wrapped object.
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonConvert.SerializeObject(responseModel));
            }
        }
    }
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class ResponseFormatterMiddlewareExtensions
{
    public static IApplicationBuilder UseResponseFormatter(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<ResponseFormatterMiddleware>();
    }
}

[Serializable]
[DataContract]
public class GenericResponseModel
{
    public GenericResponseModel(object result, HttpStatusCode statusCode, string message)
    {
        StatusCode = (int)statusCode;
        Result = result;
        Message = message;
    }
    [DataMember(Name = "result")]
    public object Result { get; set; }

    [DataMember(Name = "statusCode")]
    public int StatusCode { get; set; }

    [DataMember(Name = "message")]
    public string Message { get; set; }

    [DataMember(Name = "version")]
    public string Version { get; set; } = "V1.0"
}

这是我期望的结果:

{
    "result": null,
    "statusCode": 400,
    "message": "Name is required",
    "version": "V1"
}

,但现在观察到的结果是:

but now the observed result is:

{
    "result": {
        "Name": [
            "Name is required"
        ]
    },
    "statusCode": 400,
    "message": null,
    "version": "V1"
}


推荐答案

ModelState 仅在模型绑定之后可用。只需使用动作过滤器自动存储 ModelState ,即可在中间件中使用它。

ModelState is only available after model binding . Just store the ModelState automatically with an action filter , thus you can use it within middleware .

首先,添加一个操作过滤器,将ModelState设置为功能:

Firstly , add a action filter to set the ModelState as an feature :

public class ModelStateFeatureFilter : IAsyncActionFilter
{

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var state = context.ModelState;
        context.HttpContext.Features.Set<ModelStateFeature>(new ModelStateFeature(state));
        await next();
    }
}

此处 ModelStateFeature 是持有ModelState的虚拟类:

Here the ModelStateFeature is a dummy class that holds the ModelState:

public class ModelStateFeature
{
    public ModelStateDictionary ModelState { get; set; }

    public ModelStateFeature(ModelStateDictionary state)
    {
        this.ModelState= state;
    }
}

要使操作过滤器自动发生,我们需要配置MVC

to make the action filter take place automatically , we need configure the MVC

services.AddMvc(opts=> {
    opts.Filters.Add(typeof(ModelStateFeatureFilter));
})

现在我们可以使用 ModelState 在您的中间件中如下:

And now we can use the ModelState within your Middleware as below:

public class ResponseFormatterMiddleware
{
    // ...

    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);

            var ModelState = context.Features.Get<ModelStateFeature>()?.ModelState;
            if (ModelState==null) {
                return ;      //  if you need pass by , just set another flag in feature .
            }

            responseBody.Seek(0, SeekOrigin.Begin);
            using (var streamReader = new StreamReader(responseBody))
            {
                // Get action result come from mvc pipeline
                var strActionResult = streamReader.ReadToEnd();
                var objActionResult = JsonConvert.DeserializeObject(strActionResult);
                context.Response.Body = originBody;

               // Create uniuqe shape for all responses.
                var responseModel = new GenericResponseModel(objActionResult, (HttpStatusCode)context.Response.StatusCode, context.Items?["Message"]?.ToString());

                // => Get error message
                if (!ModelState.IsValid)
                {
                    var errors= ModelState.Values.Where(v => v.Errors.Count > 0)
                        .SelectMany(v=>v.Errors)
                        .Select(v=>v.ErrorMessage)
                        .ToList();
                    responseModel.Result = null;
                    responseModel.Message = String.Join(" ; ",errors) ;
                }

                // Set all response code to 200 and keep actual status code inside wrapped object.
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonConvert.SerializeObject(responseModel));
            }
        }
    }
}

用简单的模型进行测试

public class MyModel {
    [MinLength(6)]
    [MaxLength(12)]
    public string Name { get; set; }
    public int Age { get; set; }
}

和一个简单的控制器:

public class HomeController : Controller
{

    public IActionResult Index(string name)
    {
        return new JsonResult(new {
            Name=name
        });
    }

    [HttpPost]
    public IActionResult Person([Bind("Age,Name")]MyModel model)
    {
        return new JsonResult(model);
    }
}

如果我们发送带有有效负载的请求:

If we send a request with a valid payload :

POST https://localhost:44386/Home/Person HTTP/1.1
content-type: application/x-www-form-urlencoded

name=helloo&age=20

响应将是:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json
Server: Kestrel
X-SourceFiles: =?UTF-8?B?RDpccmVwb3J0XDIwMThcOVw5LTE4XEFwcFxBcHBcQXBwXEhvbWVcUGVyc29u?=
X-Powered-By: ASP.NET

{
  "result": {
    "name": "helloo",
    "age": 20
  },
  "statusCode": 200,
  "message": null,
  "version": "V1.0"
}

如果我们发送的请求的模型无效:

And if we send a request with an invalid model :

POST https://localhost:44386/Home/Person HTTP/1.1
content-type: application/x-www-form-urlencoded

name=hello&age=i20

响应将为

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json
Server: Kestrel
X-SourceFiles: =?UTF-8?B?RDpccmVwb3J0XDIwMThcOVw5LTE4XEFwcFxBcHBcQXBwXEhvbWVcUGVyc29u?=
X-Powered-By: ASP.NET

{
  "result": null,
  "statusCode": 200,
  "message": "The value 'i20' is not valid for Age. ; The field Name must be a string or array type with a minimum length of '6'.",
  "version": "V1.0"
}

这篇关于在Asp.net核心中间件中访问ModelState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:28