3

Web APIJSON 和 XML 媒体类型格式化程序(尤其是序列化程序)中,可以使用[JsonIgnore][DataMember]装饰器进行配置。

它仅适用于方法字段,但基类呢?有没有办法忽略或包含它的某些字段?

如果没有 - 控制序列化输出中类字段可见性的最佳方法是什么?定义指定的 JSON/XML 序列化器?Controller使用?中的选定字段将类对象转换为另一个类对象

4

1 回答 1

0

You should use a DTO that is specific for your current action and then copy the data from the DTO to the actual object you want to use.

Benefits of this is you can define validation that are specific to this action and you'll have no attributes on the business object. You can use different validation rules per action for each new DTO and still use the same business object.

If you don't want to write the mapping code to map from the DTO to the business object you can use AutoMapper.

Example code:

public enum ColourType
{
  Flat,
  Metallic
}

public class Car
{
  public void Repaint(int red, int green, int blue, ColourType colourType)
  {
    // TODO: Add some validation logic and business logic.
  }
}

public class RepainInMetallicModel
{
  [Required]
  [Range(0, 100)]
  public int Red { get; set; }

  [Required]
  [Range(0, 100)]
  public int Green { get; set; }

  [Required]
  [Range(0, 100)]
  public int Blue { get; set; }
}

public class RepaintInFlatModel
{
  [Required]
  [Range(0, 255)]
  public int Red { get; set; }

  [Required]
  [Range(0, 255)]
  public int Green { get; set; }

  [Required]
  [Range(0, 255)]
  public int Blue { get; set; }
}

public class CarController
{
  public ActionResult RepaintInMetallic(RepainInMetallicModel model)
  {
    if (ModelState.IsValid)
    {
      var car = _carsRepository.Find(model.Id);

      var.Repaint(model.Red, model.Green, model.Blue, ColourType.Metallic);

      _carsRepository.Save(car);
    }

    return View();
  }

  public ActionResult RepaintInFlat(RepaintInFlatModel model)
  {
    if (ModelState.IsValid)
    {
      var car = _carsRepository.Find(model.Id);

      var.Repaint(model.Red, model.Green, model.Blue, ColourType.Flat);

      _carsRepository.Save(car);
    }

    return View();
  }
}

The following example doesn't demonstrate the usage of AutoMapper, but it does demonstrate the usage of DTOs.

于 2013-09-04T21:23:05.290 回答