正如标题所示,我试图做的就是返回一个自定义的错误集合,如果"模型"是不完整的。
积极地" SO / google /#34;我还没有找到解决方案来帮助解决我的问题。
我可以使用" 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; }
因此忽略后两个片段,更多的是提供完整的流程概述。我完全明白有一些&#34;在盒子外面#34;技术,但我喜欢制作自己的实现。
到目前为止,是否可以使用&#34; BadRequest&#34;返回错误列表?
非常感谢。
答案 0 :(得分:4)
您可能正在寻找使用此方法:
.queryParams
它的用法是这样的,例子来自another question here in SO:
BadRequestObjectResult BadRequest(ModelStateDictionary modelState)
根据型号错误,您会得到以下结果:
if (!ModelState.IsValid)
return BadRequest(ModelState);
希望有所帮助
答案 1 :(得分:0)
在IHttpActionResult
的自定义实现中,使用请求创建响应并传递模型和状态代码。
public List<string> Messages { get; private set; }
public HttpRequestMessage Request { get; private set; }
public HttpResponseMessage Execute() {
var response = Request.CreateResponse(HttpStatusCode.BadRequest, Messages);
return response;
}
答案 2 :(得分:0)
我知道这篇文章发表的时间已经晚了,以防万一其他人有同样的需求。
我是这样做的:
public object GetModelStateErrors(ModelStateDictionary modelState)
{
var errors = new List<string>();
foreach (var state in modelState)
{
foreach (var error in state.Value.Errors)
{
errors.Add(error.ErrorMessage);
}
}
var response = new { errors = errors };
return response;
}
如您所见,GetModelStateErrors
是一个函数,该函数返回带有您已收集的错误的字符串数组,并接收ModelState
对象以从中获取这些错误。
我是这样实现的:
return Request.CreateResponse(HttpStatusCode.BadRequest, GetModelStateErrors(ModelState))
我使用失眠症的反应是:
{
"errors": [
"The Correo field is required.",
"The Telefono field is required."
]
}
希望有帮助