【问题标题】:Web APIs methods with Warnings带有警告的 Web API 方法
【发布时间】:2014-05-22 14:36:15
【问题描述】:

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

在 Web API 中最好的方法是什么?还是应该将方法分为两种,一种用于验证,一种用于保存?

【问题讨论】:

  • 为什么只是为了验证而在客户端和服务器之间来回切换?我会在客户端进行验证,确保一切正常,让他们确认任何选项和警告,然后发送您的帖子。
  • @gitsitgo:应始终在双方进行验证。任何人都可以发出 HTTP 请求,而不仅仅是您的网站。
  • @jgauffin 是的,但是 OP 正在讨论“警告”上下文中的验证,这应该在发出任何请求之前在客户端完成。

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


【解决方案1】:

按以下方式设置您的 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 结果。

【讨论】:

    【解决方案2】:

    我创建并使用一个包装器,其中包含要绑定到 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);
             }                          
        }
    

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

    【讨论】:

      猜你喜欢
      • 2011-08-18
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 2011-06-08
      相关资源
      最近更新 更多