【发布时间】:2018-02-02 00:35:57
【问题描述】:
我在 Aspnet Core 1.1 中编写了一个 API,但其中一个要求是每个请求都必须是对单个路由的发布请求,并且根据主体有效负载中的类型加载一个动作,我尝试继承 ActionMethodSelectorAttribute 并实现 @ 987654322@ 然后装饰每个传递预期类型的 Action 这是一种简单的方法,它可以工作,但是当我尝试使用 RouteContext.HttpContext.Request.Body 它是一个 Stream 对象时出现问题,如果我尝试多次反序列化它会抛出和异常,我还使用了缓存,这帮助我避免了异常,但是一旦选择了 Action,body 就已经消耗掉了,无法再次用于序列化它并用于模型绑定。
public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
try
{
var body = new MemoryStream();
routeContext.HttpContext.Request.Body.CopyTo(body);
body.Position = 0;
XmlDocument xmlDoc = new XmlDocument();
var xml = XDocument.Load(body);
var messageName = xml.Root.Name.LocalName;
return messageName == _messageType.Name;
}
catch (Exception ex)
{
return false;
}
}
[MessagBasedControllerActionSelector(typeof(OTA_HotelInvCountRQ))]
public async Task<IActionResult> OTA_HotelInvCount([FromBody]OTA_HotelInvCountRQ request)
{
var response = await _otaService.OTA_HotelInvCountRQ(request, GetExternalProviderId());
return Ok(response);
}
我知道这种方法无法扩展,我很乐意听取另一种解决方案或满足我要求的解决方案。
【问题讨论】:
标签: c# asp.net-core asp.net-core-webapi