c# - 从 web api 返回 bool 值

标签 c# asp.net api httpresponse

我正在使用 Web Api 2 创建 1 个用户。下面是代码

[HttpPost]
public HttpResponseMessage UpdateUserData(User user)
{                            
    try
    {
        //Code
        .
        .
        user.Update();
        return Request.CreateResponse(HttpStatusCode.OK, true);
    }
    catch (Exception ex)
    {
        ExceptionLogger.LogException(ex);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "error");
    }
}

我试图从后面的代码中调用这个方法

using (HttpClient client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:65486/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var response = client.PostAsJsonAsync("api/Stock/UpdateUserData", userObject).Result;

    if (response.IsSuccessStatusCode)
    {
        using (HttpContent content = response.Content)
        {
            Task<string> result = content.ReadAsStringAsync();
            string final = result.Result;
        }  
    }
    else
    {
        //code
    }
}

现在我有几个问题了

  • 我们能否在 HttpResponseMessage 中返回 bool 值 true/false。我是说 在 CreateErrorResponse 中。

  • 检查用户是否更新的最佳方法是什么?

  • 这段代码可以改进吗?

最佳答案

1) 我们可以在 HttpResponseMessage 中返回 bool 值 true/false。我的意思是在 CreateErrorResponse 中?

从技术上讲,您有以下选择

a) CreateErrorResponse 将创建 HttpError 对象。

return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, false.ToString());

序列化响应将是

 {"Message":"False"}

b) 或者你可以

return Request.CreateResponse(HttpStatusCode.InternalServerError, false.ToString());

响应将是

"False"

2) 检查用户是否更新的最佳方法是什么? 3)这段代码可以改进吗?

在我看来,最好让你的 api 与 REST 推荐保持一致 http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

通常 REST post api 返回创建的资源。前-

[HttpPost]
public HttpResponseMessage UpdateUserData(User user)
{                            
    try
    {
        // Validate user 
        // if invalid request return Request.CreateErrorResponse(HttpStatusCode.BadRequest, validationErrorMessage);

        //Code to change user
        user.Update();
        return Request.CreateResponse(HttpStatusCode.Created, user);
    }
    catch (Exception ex)
    {
        ExceptionLogger.LogException(ex);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "error");
    }
}

如果响应是 201 以外的任何内容,则表示创建用户时出错。错误详细信息应在消息中。

关于c# - 从 web api 返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44386416/

相关文章:

c# - 基本继承错误,哪些参数?

c# - 每个 Web 请求一个 DbContext ......为什么?

java - 在hadoop(2.2.0)中使用新的api和工具接口(interface)

C# OPOS 通用控制对象向后兼容服务对象

c# - ASP.NET Web API - 测试错误 : an error has occurred - how to fix it?

C# 嵌套异步方法

c# - 手动 Windows 身份验证

jquery - Facebook 类似自动完成文本框,每个标签中带有关闭按钮(在 ASP.NET 中)

api - 我的 URI 应该如何构建才能被视为 RESTful?

java - 如何使用 j2me APIBridge 访问移动收件箱、通话记录、照片库?