c# - 使用 BadRequest (WebApi) 返回错误列表

标签 c# asp.net-web-api2

正如标题所示,如果“模型”不完整,我要做的就是返回一个自定义的错误集合。

虽然积极地“搜索/谷歌搜索”,但我还没有找到解决问题的方法。

我本来可以使用“ModelState”,但由于“自定义”,我想手动执行此操作。

代码如下:

API 级别

// POST api/<controller>
[HttpPost]
[Route("")]
public async Task<IHttpActionResult> Post([FromBody]Order order)
{
    var modelResponse = new ModelResponse<Order>(order);
    if (order == null)
        return BadRequest("Unusable resource, object instance required.");

    //Check if all required properties contain values, if not, return response
    //with the details
    if (!modelResponse.IsModelValid())
        return this.PropertiesRequired(modelResponse.ModelErrors());

    try
    {
        await _orderService.AddAsync(order);
    }
    catch (System.Exception ex)
    {
        return InternalServerError();
    }
    finally
    {
        _orderService.Dispose();
    }

    return Ok("Order Successfully Processed.");
}

需要操作结果的属性

public List<string> Messages { get; private set; }
public HttpRequestMessage Request { get; private set; }

public PropertiesRequiredActionResult(List<string> message, 
    HttpRequestMessage request)
{
    this.Messages = message;
    this.Request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
    return Task.FromResult(Execute());
}

public HttpResponseMessage Execute()
{
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);
    response.Content = new ObjectContent()
        //new List<StringContent>(Messages); //Stuck here
    response.RequestMessage = Request;
    return response;
}

根据自定义属性查找不完整的属性

private T _obj;

public ModelResponse(T obj)
{
    _obj = obj;
}

private Dictionary<string, object> GetPropertyAttributes(PropertyInfo property)
{
    Dictionary<string, object> attribs = new Dictionary<string, object>();
    // look for attributes that takes one constructor argument
    foreach (CustomAttributeData attribData in property.GetCustomAttributesData())
    {

        if (attribData.ConstructorArguments.Count == 1)
        {
            string typeName = attribData.Constructor.DeclaringType.Name;
            if (typeName.EndsWith("Attribute")) typeName = typeName.Substring(0, typeName.Length - 9);
            attribs[typeName] = attribData.ConstructorArguments[0].Value;
        }

    }
    return attribs;
}
private IEnumerable<PropertyInfo> GetProperties()
{
    var props = typeof(T).GetProperties().Where(
            prop => Attribute.IsDefined(prop, typeof(APIAttribute)));

    return props;
}
public bool IsModelValid()
{
    var props = GetProperties();
    return props.Any(p => p != null);
}
public List<string> ModelErrors()
{
        List<string> errors = new List<string>();
        foreach (var p in GetProperties())
        {

            object propertyValue = _obj.GetType()
                .GetProperty(p.Name).GetValue(_obj, null);

            if (propertyValue == null)
            {
                errors.Add(p.Name + " - " + GetPropertyAttributes(p).FirstOrDefault());
            }
        }
        return errors;
}

属性样本

/// <summary>
/// The date and time when the order was created.
/// </summary>
[API(Required = "Order Created At Required")]
public DateTime Order_Created_At { get; set; }

所以忽略后两个片段,这更像是一个完整的过程概述。我完全理解有一些“开箱即用”的技术,但我确实喜欢制作自己的实现。

至此,是否可以使用“BadRequest”返回错误列表?

非常感谢。

最佳答案

您可能正在寻找使用这种方法:

BadRequestObjectResult BadRequest(ModelStateDictionary modelState)

用法是这样的,例子来自another question here in SO :

if (!ModelState.IsValid)
     return BadRequest(ModelState);

根据模型错误,您会得到以下结果:

{
   Message: "The request is invalid."
   ModelState: {
       model.PropertyA: [
            "The PropertyA field is required."
       ],
       model.PropertyB: [
             "The PropertyB field is required."
       ]
   }
}

希望对你有帮助

关于c# - 使用 BadRequest (WebApi) 返回错误列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42201644/

相关文章:

c# - 在异步操作中的 TransactionScope 的 WebAPI 中使用自定义 IHttpActionInvoker

c# - 重新附加实体图并检测集合更改

c# - 将 Global.asax 迁移到 Startup.cs

c# - 如何确定一个字符串是否是用户 SID?

c# - 在 asp net core 中编辑查询字符串

c# - Microsoft Owin 日志记录 - Web Api 2 - 如何创建记录器?

OData V4 System.DateTime 重大更改

c# - 如何从 IOwinContext 获取 HttpRequestBase

c# - 将 CSV 加载到 DataGridView 中

c# - configuration.GetValue 列表返回 null