How do I add properties to a Web API Response that I do not store in my DB?

白昼怎懂夜的黑 提交于 2019-12-02 03:53:31

I would go with more generic approach:

public class MyResponse<T>
{
    public T Data {get;set;}
    public Status ResponseStatus{get;set;}
    public string Message{get;set;}
}

This way you can handle all you models/data in the same way.

UPDATE

[AllowAnonymous]
[RoutePrefix("api/home")]
public class HomeController : ApiController
{
    [HttpGet]
    [Route("ok")]
    public MyResponse<MyUser> OK()
    {
        MyUser m = new MyUser();
        var r = MyResponse<MyUser>.Success(m);
        return r;
    }

    [Route("nok")]
    [HttpGet]
    public MyResponse<MyUser> NOK()
    {
        var r = MyResponse<MyUser>.Error("something went terribly wrong");
        return r;
    }
}

public class MyResponse<T>
{
    public T Data { get; set; }
    public Status ResponseStatus { get; set; }
    public string Message { get; set; }

    private MyResponse() { }

    public static MyResponse<T> Success(T data)
    {
        return new MyResponse<T> { Data = data, ResponseStatus = Status.Success };
    }

    public static MyResponse<T> Error(string message)
    {
        return new MyResponse<T> { ResponseStatus = Status.Error, Message = message };
    }
}

public class MyUser
{
    public int Id { get; set; }
    public string Name { get; set; }
}


public enum Status
{
    Unknown = 0,
    Success = 1,
    Error
}

Ideally you should create a data transfer object (DTO) class in model with all the properties you require, then use a mapper to map your user to the DTO

public class UserDto{
   public string UserID {get; set;}
   public string FirstName {get; set;}
   public string LastName {get; set;}

   public string Message {get; set;}
   public string Status {get; set;}
}

Then in your action

[ResponseType(typeof(UserDto))]
public IHttpActionResult User(string userId){

   // retrive user from db

   var userDto = Mapper.Map<UserDto>(dbUser);

   if(condition){
      userDto.Message = "the message";
      userDto.Status = "the status";
   }

   return Ok(userDto);
}

Then you can install Automapper to from nuget and configure it to do the mapping for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!