2015-06-03 34 views
0

我在ASP.NET MVC應用程序中使用WebAPI Datacontrollers並想知道什麼是放置服務器端偏差的最佳做法?WebAPI HTTPPost數據驗證

1)在API控制器本身? 2)在數據插入前(源級別)?

而應該如何迴應客戶?

回答

1

在網頁API控制器,你可以驗證你的模型像下面的代碼:

using System.ComponentModel.DataAnnotations; 
namespace MyApi.Models 
{ 
    public class Product 
    { 
     public int Id { get; set; } 
     [Required] 
     public string Name { get; set; } 
     public decimal Price { get; set; } 
     [Range(0, 999)] 
     public double Weight { get; set; } 
    } 
} 

和您的文章的行動將是這樣的:

using MyApi.Models; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 
namespace MyApi.Controllers 
{ 
    public class ProductsController : ApiController 
    { 
     public HttpResponseMessage Post(Product product) 
     { 
      if (ModelState.IsValid) 
      { 
       // Do something with the product (not shown). 

       return new HttpResponseMessage(HttpStatusCode.OK); 
      } 
      else 
      { 
       return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); 
      } 
     } 
    } 
} 

試試這個,它會爲你工作。 欲瞭解更多詳情,請參閱此鏈接:Model Validation in Web API