【问题标题】:How to display WCF HTTP codes in service response如何在服务响应中显示 WCF HTTP 代码
【发布时间】:2015-06-19 22:40:49
【问题描述】:

我正在使用 WCF 和实体框架处理 Web 服务,我想知道如何查看 HTTP 状态代码或将其返回给调用客户端。

我的代码如下:

IUserService.cs

   [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "/GetUsers")]
        List<User> GetUsers();

UserService.svc.cs

  public List<User> GetUsers()
        {
            var userController = new UserController();
            return userController.GetUsers();
        }

用户控制器.cs

 public List<User> GetUsers()
        {
            List<User> serverResponse = new List<User>();

            try
            {
                using (var db = new MyEntities())
                {
                  List<user> userList = db.users.ToList();

                    foreach (user userRecord in userList)
                    {
                        User userDto = new User();
                        userDto.userId = userRecord.user_id;
                        userDto.name = userRecord.user_name;
                        serverResponse.Add(userDto);
                    }
                }
            }

            catch (Exception ex)
            {

            }

            return serverResponse;

用户 DTO

  [DataContract]
    public class User
    {
        [DataMember(Name = "name")]
        public string name { get; set; }

        [DataMember(Name = "userId")]
        public int userId { get; set; }

    }

我在使用或处理其他 API 时看到,状态代码可以在响应之类的字典中返回,例如客户端调用响应中键值对中的“成功”“200”。有没有办法在 web.Config 或 Interface 类中为 WCF 启用类似的功能?我希望客户端能够接收成功或失败的错误代码,以便在出现问题时能够做出反应。当我在浏览器中运行此请求时,我会返回以下有效 JSON:

 [
    {
        "name": "APIClientTestUser",
        "userId": 212,
    }
]

无论是使用此 JSON 还是其他地方,我都希望客户端知道调用成功或失败并使用适当的 HTTP 代码。任何有关如何执行此操作的提示或建议将不胜感激。

【问题讨论】:

    标签: c# json entity-framework wcf rest


    【解决方案1】:

    可能最简单的方法是将您的结果包装到通用响应对象中

    [DataContract]
    public class Response<T>
    {
        [DataMember]
        public T Result { get; set; }
    
        [DataMember]
        public int Status { get; set; }
    }
    
    // then your declaration
    Response<List<User>> serverResponse = Response<List<User>>();
    
    // on success
    serverResponse.Result = userList;
    serverResponse.Status = 200; // ok
    
    // on fail
    serverResponse.Status = 500; // fail
    
    // and contract
    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "/GetUsers")]
    Response<List<User>> GetUsers();
    

    【讨论】:

    • 谢谢,这正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 2017-08-07
    • 2016-05-19
    相关资源
    最近更新 更多