带有警告的Web API方法

时间:2014-05-22 14:36:16

标签: asp.net asp.net-mvc web-services asp.net-web-api

我在用于创建记录的POST中使用此方法,但在将该记录插入数据库之前,我必须做一些验证,我可能会回来警告,我需要将这些警告返回给客户确认回来。

在Web API中执行此操作的最佳方法是什么?或者我应该将方法拆分为2,一个用于验证,一个用于保存?

2 个答案:

答案 0 :(得分:0)

按以下方式设置您的Web Api。

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

您验证发送给API的对象会发生什么。如果验证失败,则返回请求不正确,并显示您指定的消息。

验证成功后,将调用插入逻辑,并在成功时返回OK结果。

答案 1 :(得分: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);
         }                          
    }

这样您的响应对象仍然会在逻辑层中添加警告,并且根据返回的状态代码,您可以在客户端处理这些消息。