2017-02-17 46 views
2

假設您向控制器發送了一個類實例,並且該類具有Enum類型的屬性。驗證Web API中的枚舉2對象參數

public class CoffeeController : ApiController 
{ 
    [HttpPost] 
    public async Task<IHttpActionResult> OrderAsync(Order request) 
    { 
     return Ok(); 
    } 
} 

public enum CoffeeType 
{ 
    Latte, 
    Mocha, 
    Espresso 
} 

public class Order 
{ 
    public CoffeeType Type { get; set; } 
    public string Name { get; set; } 
} 

如果請求中的枚舉成員的名稱有錯誤,應用程序不會拋出異常。它使用默認的枚舉值代替:

{"name":"Dan", 'type':"ocha"}=>{"Name":"Dan", "Type":"Latte"} 

這對我來說似乎很奇怪。 爲什麼會使用這種行爲?

有沒有優雅的方式來拋出錯誤?

回答

0

正如Brett寫的,你可以使用ModelState.IsValid和ModelState會有錯誤。 如果你只需要扔你可以使用自定義介質格式化你的類型,像一個錯誤:

public class OrderJsonFormatter : BufferedMediaTypeFormatter 
    { 
     public OrderJsonFormatter() 
     { 
      SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); 
     } 

     public override bool CanReadType(Type type) 
     { 
      var canRead = type == typeof(Order); 
      return canRead; 
     } 

     public override bool CanWriteType(Type type) 
     { 
      return false; 
     } 

     public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) 
     { 
      return this.ReadFromStream(type, readStream, content, formatterLogger, CancellationToken.None); 
     } 

     public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken) 
     { 
      using (var reader = new StreamReader(readStream)) 
      { 
       using (var jsonReader = new JsonTextReader(reader)) 
       { 
        var jsonSerializer = new JsonSerializer(); 

        if (type == typeof(Order)) 
        { 


         try 
         { 
          var entity = jsonSerializer.Deserialize<Order>(jsonReader); 
          return entity; 
         } 
         catch (Exception ex) 
         { 
         //log error here 
          throw; 
         } 
        } 

        return null; 
       } 
      } 
     } 


    } 

,並將其註冊:

GlobalConfiguration.Configuration.Formatters.Insert(0, new OrderJsonFormatter()); 
0

它這樣做是因爲枚舉是基於整數類型,所以它們會一直有一個值(值類型不能爲null)和將默認爲0。使用以下解決方法

public enum CoffeeType 
{ 
    Invalid = 0 
    Latte = 1, 
    Mocha = 2, 
    Espresso = 3 
} 
1

應用驗證您的楷模。創建一個ActionFilterAttribute並將其連接到您的管道或使用它裝飾您的端點。建議您還考慮FluentValidation作爲一個偉大的圖書館來執行驗證。

請參閱ValidateModelStateFilter例如this article的一個很好的例子。