2014-05-22 5 views
0

레코드를 만들기 위해 POST를 수행하는 API에서이 메서드를 사용하지만 DB에 해당 레코드를 삽입하기 전에 내가 수행해야하는 유효성 검사가 몇 가지 있습니다. 경고가 표시 될 수 있으며 반환해야합니다. 다시 확인하기 위해 이러한 경고를 클라이언트에 보냅니다.경고가있는 웹 API 메서드

웹 API에서 가장 좋은 방법은 무엇입니까? 또는 내가 2, 하나의 검증 및 저장을위한 방법으로 분할해야합니까?

+0

유효성 검사를 위해 클라이언트와 서버간에 앞뒤로 이동하는 이유는 무엇입니까? 나는 클라이언트 쪽에서 유효성 검사를 할 것이고, 모든 것이 잘되었는지 확인하고, 옵션과 경고를 확인하도록 한 다음, 귀하의 게시물을 보내 게하십시오. – gitsitgo

+0

@gitsitgo : 항상 양측에서 확인해야합니다. 누구나 웹 사이트가 아닌 HTTP 요청을 할 수 있습니다. – jgauffin

+0

@jgauffin 네,하지만 OP는 "경고"의 컨텍스트에서 유효성 검사를 말합니다. 이것은 요청이 있기 전에 클라이언트 측에서 수행되어야합니다. – gitsitgo

답변

0

다음과 같은 방법으로 웹 API를 설정하십시오.

[HttpPost] 
public IHttpActionResult DoStuff(object item) 
{ 
    if(!validate(item)) 
    { 
     return this.BadRequest("Validation failed blablabla"); 
    } 
    else 
    { 
     //insert logic 
    } 
    return this.Ok(); 
} 

어떻게하면 API에 보내는 개체의 유효성을 검사 할 수 있습니다. 응답을 확인하지 못하면 요청한 메시지가 올바르지 않습니다.

유효성 검사가 성공하면 삽입 논리가 호출되고 성공하면 OK 결과를 반환합니다.

0

필자는 UI에 바인딩 할 객체, 메시지 (오류 또는 유효성 검사 또는 경고) 및 합계를 포함하는 래퍼를 만들고 사용합니다.

/// <summary> 
    /// Class for the Repository response object 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    public class CLSResponse<T> 
    { 

    /// <summary> 
    /// Gets or sets the messages to be returned in the response. 
    /// </summary> 
    /// <value>The messages.</value> 
    public IEnumerable<KeyValuePair<string, string>> Messages { 
    get { return m_Messages; } 
    set { m_Messages = value; } 
    } 

    private IEnumerable<KeyValuePair<string, string>> m_Messages; 
    /// <summary> 
    /// Gets or sets the service model to be returned in the response. 
    /// </summary> 
    /// <value>The service model.</value> 
    public T ServiceModel { 
    get { return m_ServiceModel; } 
    set { m_ServiceModel = value; } 
    } 

    private T m_ServiceModel; 
    /// <summary> 
    /// Gets or sets the totalitems. 
    /// </summary> 
    /// <value>The TotalItems.</value> 
    public int TotalItems { 
    get { return m_TotalItems; } 
    set { m_TotalItems = value; } 
    } 

    private int m_TotalItems; 
    /// <summary> 
    /// Gets and Sets the Message Type based on the MessageType Struct 
    /// </summary> 

    public string MessagesType; 
     } 


     /// <summary> 
     /// Struct for MessageTypes to be returned with messages, in the response object 
     /// </summary> 
     public struct MessagesType 
     { 
     /// <summary> 
     /// Validation 
     /// </summary> 

     public static string Validation = "Validation"; 
     /// <summary> 
     /// Warning 
     /// </summary> 

     public static string Warning = "Warning"; 
     /// <summary> 
     /// Error 
     /// </summary> 

     public static string Error = "Error"; 
     /// <summary> 
     /// Unauthorized 
     /// </summary> 
     public static string UnAuthorized = "Unauthorized"; 
     } 

그런 다음 저장소 층 또는 로직 계층에서

컨트롤러에 이제
public CLSResponse<bool> CreateUser(string request) 
    { 
     var messages = new List<KeyValuePair<string, string>>(); 
     try 
      { 
       //Do something 
       if (!validation) 
       { 
        messages.Add(MessagesType.Validation, "Invalid"); 
        return new CLSResponse<bool> { 
      ServiceModel = false, 
      Messages = messages, 
      MessagesType = MessagesType.Validation 
     }; 
       } 
       else {   
       return new CLSResponse<bool> { 
      ServiceModel = true, 
      Messages = messages, 
      MessagesType = MessagesType.Error 
      }; 
     } 
     } 
      catch (Exception ex) 
      { 
      messages.Add(MessagesType.Error, "UpdateFailed"); 
     return new CLSResponse<bool> { 
     ServiceModel = false, 
     Messages = messages, 
     MessagesType = MessagesType.Error 
     }; 
     } 
     } 

,

[HttpPost] 
    public HttpResponseMessage<CLSResponse<bool>> CreateUser(string input) 
    { 
     var res = LogicLayer.CreateUser(input); 
     //Check for res.MessageType and set the status code 
     if (res.MessagesType = MessagesType.Validation) 
     { 
      return Request.CreateResponse<CLSResponse<bool>>(HttpStatusCode.PreconditionFailed, res); 
     }       
    } 

응답 객체가 여전히 로직 계층과에 따라 추가 경고를 가지고이 방법 상태 코드가 반환되면 클라이언트 쪽에서 해당 메시지를 처리 ​​할 수 ​​있습니다.

관련 문제