在.Net Core的Startup.cs类中设置StatusCode

时间:2019-07-23 12:22:10

标签: c# asp.net-web-api dependency-injection .net-core

我想在Startup.cs中返回StatusCode并返回带有response.ResponseCode和response.Responsedata的FluentValidation消息,与下面的代码相同。

控制器代码:

public async Task<IActionResult> Get()  
{
       BaseResponse<Employee> response;
        //populate response 
       response.Responsedata = new List<Employee> { };      
            return StatusCode(response.ResponseCode, new { Data = response });
}

Startup.cs

services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = (context) =>
                {
                    var errors = context.ModelState.Values.SelectMany(x => x.Errors.Select(p => p.ErrorMessage)).ToList();
                    var result = new
                    {
                        Code = "00009",
                        Message = "Validation errors",
                        Errors = errors
                    };
                    return new BadRequestObjectResult(result);
                };
            });

0 个答案:

没有答案