C# 使用RESTAPI响应错误用户输入的推荐方法是什么?
让我们假设如下:C# 使用RESTAPI响应错误用户输入的推荐方法是什么?,c#,json,rest,xamarin,C#,Json,Rest,Xamarin,让我们假设如下: 我有一个RESTAPI,它将返回水果的名称,只有5个水果 要知道水果的名字,我必须要一个ID 考虑以下代码: public class Fruit { public int FruitID { get; set; } public string FruitName { get; set; } public Fruit(string json){ JObject o = JObject.Parse(json); Frui
- 我有一个RESTAPI,它将返回水果的名称,只有5个水果
- 要知道水果的名字,我必须要一个ID
public class Fruit {
public int FruitID { get; set; }
public string FruitName { get; set; }
public Fruit(string json){
JObject o = JObject.Parse(json);
FruitID = Int32.Parse((string) o["id"]);
FruitName = (string) o["name");
}
}
public static Fruit getFruit(int id){
Task<Fruit> task = "http://fruit.com/get_fruit"
.SetQueryParams(new { fruit_id = id })
.GetStringAsync();
return new Fruit(task.Result);
}
或者,如果它收到了无效的ID
{
"status":0
}
如果用户应该输入要搜索的ID,那么他们有可能输入一个不存在的ID,因为只有5个(0到4)。根据我在上面输入的代码,如果返回“status”:0
,我可以看到应用程序崩溃,因为它没有类构造函数要查找的两个字段
我的问题是:处理可能的无效输入(例如用户输入的ID为20)的最佳方法是什么?RESTful API的建议方法是使用HTTP错误代码,在您的情况下,它将是404(未找到),因为请求的结果不存在。 您应该在尝试创建对象之前处理错误代码。因此,请检查请求是否已成功执行(200 OK),然后处理有效负载 以下是状态代码的参考:
RESTful API的推荐方法是使用HTTP错误代码,在您的情况下,它将是404(未找到),因为请求的结果不存在。 您应该在尝试创建对象之前处理错误代码。因此,请检查请求是否已成功执行(200 OK),然后处理有效负载 以下是状态代码的参考:
输入验证是web服务开发中的重要任务之一。我个人有两个阶段。首先,我检查对象的空值。我写这个方法就是为了做到这一点:
private bool HasNull(object webServiceInput, string[] optionalParameters = null)
{
if (ReferenceEquals(null, webServiceInput))
return false;
if (optionalParameters == null)
optionalParameters = new string[0];
var binding = BindingFlags.Instance | BindingFlags.Public;
var properties = webServiceInput.GetType().GetProperties(binding);
foreach (var property in properties)
{
if (!property.CanRead)
continue;
if (property.PropertyType.IsValueType)
continue;
if (optionalParameters.Contains(property.Name))
continue;
var value = property.GetValue(webServiceInput);
if (ReferenceEquals(null, value))
return false;
}
return true;
}
然后,如果一些输入应该指定了验证,我会单独检查它。例如,我检查ID是否介于0和5之间;
我希望它能帮助您。输入验证是web服务开发中的重要任务之一。我个人有两个阶段。首先,我检查对象的空值。我写这个方法就是为了做到这一点:
private bool HasNull(object webServiceInput, string[] optionalParameters = null)
{
if (ReferenceEquals(null, webServiceInput))
return false;
if (optionalParameters == null)
optionalParameters = new string[0];
var binding = BindingFlags.Instance | BindingFlags.Public;
var properties = webServiceInput.GetType().GetProperties(binding);
foreach (var property in properties)
{
if (!property.CanRead)
continue;
if (property.PropertyType.IsValueType)
continue;
if (optionalParameters.Contains(property.Name))
continue;
var value = property.GetValue(webServiceInput);
if (ReferenceEquals(null, value))
return false;
}
return true;
}
然后,如果一些输入应该指定了验证,我会单独检查它。例如,我检查ID是否介于0和5之间;
我希望它能帮助您。我知道您来自哪里,除了我使用的API没有返回404。它返回一个
“状态”:0
。我可以和API经理谈谈这个问题。虽然想法类似,但您应该在实体之前处理状态。在该示例中,检查状态是否为“1”,然后解析结果,否则处理错误状态(0),我知道您来自何处,但我使用的API不返回404。它返回一个“状态”:0
。我可以和API经理谈谈这个问题。虽然想法类似,但您应该在实体之前处理状态。在该示例中,检查状态是否为“1”,然后解析结果,否则处理错误状态(0)