我有一个对通过服务代理调用的OData Web API的批处理请求:
_productService.AttachTo("Products", product1);
_productService.UpdateObject(product1);
_productService.AttachTo("Products", product2);
_productService.UpdateObject(product2);
_productService.AttachTo("Products", product3);
_productService.UpdateObject(product3);
_productService.SaveChanges(SaveChangesOptions.Batch);
这将击打ProductsController的patch方法。具体来说,如果请求无效,则返回BadRequest行:
public IHttpActionResult Patch([FromODataUri] int key, Delta<Product> patch)
{
Product product = db.Products.Find(key);
patch.Patch(product);
HttpActionContext actionContext = new HttpActionContext(ControllerContext, Request.GetActionDescriptor());
if (!Configuration.Services.GetBodyModelValidator().Validate(maintenance, typeof(Product), Configuration.Services.GetModelMetadataProvider(), actionContext, String.Empty))
{
return BadRequest(actionContext.ModelState);
}
else
{
引发一条错误消息,其类型为DataServiceRequestException。它的Response属性包含System.Data.Services.Client.ChangeOperationResponse的集合。这些每个都有错误, header 和StatusCode属性。我的问题是错误属性是一个xml字符串。
<?xml version="1.0" encoding="utf-8"?>
<m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<m:code />
<m:message xml:lang="en-US">The request is invalid.</m:message>
<m:innererror>
<m:message>BookedForDate : 'Booked For Date' must not be empty.
\n</m:message>
<m:type></m:type>
<m:stacktrace></m:stacktrace>
</m:innererror>
</m:error>
我想提取其中的某些部分以返回给客户端。
我必须解析XML还是有一种方法可以将其作为Exception对象返回或将其强制转换为对象?
感谢您的帮助或想法。
最佳答案
我使用了类似的方法来返回错误的消息部分。查询节点时,您必须查看内部异常并使用 namespace ,否则不返回任何内容。
var doc = XDocument.Parse(e.InnerException.Message);
var msg =来自doc.Root.Elements(doc.Root.GetDefaultNamespace()+ innererror“)中的节点。Elements(doc.Root.GetDefaultNamespace()+” message“)
选择node.Value;
返回msg.LastOrDefault();
关于c# - Web API 2 OData错误消息作为XML返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24036548/