我正在设计一个ASP.Net Webapi 2解决方案,该解决方案可能会从[Frombody]接收请求消息的一种形式,如下所示。
我应该如何设计将绑定到传入请求消息的具体类?任何建议将不胜感激。
<?xml version="1.0" encoding="utf-8"?>
<RequestMessage>
<Shapes>
<RectangleInfo></RectangleInfo>
</Shapes>
</RequestMessage>
or
<RequestMessage>
<Shapes>
<CicleInfo></CicleInfo>
</Shapes>
</RequestMessage>
or
<RequestMessage>
<Shapes>
<SquareInfo></SquareInfo>
</Shapes>
</RequestMessage>
答案 0 :(得分:0)
请考虑使用ModelBinder接口并返回正确类型的IShape:RectangleShape,CicleShape或SquareShape。完成后,您的控制器方法将如下所示:
public Task<HttpResponseMessage> GetShape(
[ModelBinder] IShape shape = null) { ... }
您的资料夹看起来像
using System;
using System.Net;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
/// <summary>Web API ModelBinder for Shape.</summary>
/// <example>
/// At service startup include:
/// config.Services.Insert(typeof(ModelBinderProvider), 0, new SimpleModelBinderProvider(typeof(IShape), new ShapeBinder()));
/// <br/>
/// On controller methods that need a IShape
/// public async Task<HttpResponseMessage> SomeMethod([ModelBinder] IShape shape)
/// </example>
public class ShapeBinder : IModelBinder
{
/// <summary>Create a Shape.</summary>
/// <returns>true if a valid shape . false otherwise.</returns>
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(IShape))
{
return CreateShape(actionContext, bindingContext);
}
return false;
}
您的班级层次结构将类似于
public abstract class Shape : IShape { .. properties for all shapes ... }
public class SquareShape : RectangleShape { ... special case rectangle syntactic sugar that makes it a square ... }
public class RectangleShape : Shape { ... rectangle properties }
public class CicleShape : Shape { ... cicle properties }
您甚至有一天可能会添加
public class CircleShape : EllipseShape { ... circle special case of ellipse properties ... }
public class EllipseShape : Shape { ... ellipse properties ... }
也许答案与您所想的不同,但是您说了Any suggestion
,这可能会为您提供很好的服务。