Tez*_*eld 4 c# asp.net-web-api2
如标题所示,如果“模型”不完整,我将尝试返回所有错误的自定义集合。
尽管积极地进行“ SO'ing / Google搜索”,但我还没有找到解决我的问题的解决方案。
我可以使用“ 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.");
}
Run Code Online (Sandbox Code Playgroud)
需要的属性操作结果
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;
}
Run Code Online (Sandbox Code Playgroud)
根据自定义属性查找不完整的属性
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;
}
Run Code Online (Sandbox Code Playgroud)
属性样本
/// <summary>
/// The date and time when the order was created.
/// </summary>
[API(Required = "Order Created At Required")]
public DateTime Order_Created_At { get; set; }
Run Code Online (Sandbox Code Playgroud)
因此,忽略后面的两个代码片段,更多的是提供完整的过程概述。我完全理解有一些“开箱即用”的技术,但我确实喜欢精心设计自己的实现。
到目前为止,是否可以使用“ BadRequest”返回错误列表?
非常感激。
您可能正在寻找使用此方法的方法:
BadRequestObjectResult BadRequest(ModelStateDictionary modelState)
Run Code Online (Sandbox Code Playgroud)
它的用法是这样的,示例来自SO中的另一个问题:
if (!ModelState.IsValid)
return BadRequest(ModelState);
Run Code Online (Sandbox Code Playgroud)
根据模型错误,您将获得以下结果:
{
Message: "The request is invalid."
ModelState: {
model.PropertyA: [
"The PropertyA field is required."
],
model.PropertyB: [
"The PropertyB field is required."
]
}
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你
在您的自定义实现中,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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8696 次 |
| 最近记录: |