在REST Web API调用中返回复杂对象

Mic*_*ern 9 rest asp.net-mvc asp.net-web-api

我有一个Web API POST方法,它将自定义复杂对象MyObjectRequest作为参数排除,并返回一个自定义复杂对象MyObjectResponse.该MyObjectResponse对象具有自定义复杂对象Token作为属性.

public class MyObjectRequest
{
   public string AppName { get; set; }
   public string Username { get; set; }
   public string Password { get; set; }
   public string AppIdentifier { get; set; }
}

public class MyObjectResponse
{
   public bool Authenticated { get; set; }
   public Token AccessToken { get; set; }
}

public class Token
{
   public string Id { get; set; }
   public string ExpirationDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有Web API控制器,当用户进行HTTP POST调用时,我想返回MyObjectResponse.

public class MyCustomController : Controller
{
    public MyObjectResponse Post([FromBody] MyObjectRequest request)
    {
        //do my work here
    }
}
Run Code Online (Sandbox Code Playgroud)

这是制作我的MyCustomControllerAPI签名的正确方法吗?

Yog*_*raj 14

你有什么可以工作的.我倾向于将这些对象包装在HttpResponseMessage下面:

[HttpPost]
public HttpResponseMessage Post([FromBody] MyObjectRequest request)
{
    if (ModelState.IsValid) // and if you have any other checks
    {
        var myObjectResponse = new MyObjectResponse(); 
        // In your case, this will be result of some service method. Then...

        return Request.CreateResponse(HttpStatusCode.Created, myObjectResponse);
    }
    return Request.CreateResponse(HttpStatusCode.BadRequest);       
}

[HttpPut]
public HttpResponseMessage Update([FromBody] UserModel userModel)
{
    if (ModelState.IsValid)
    {
        var myObjectResponse = new MyObjectResponse();
        // In your case, this will be result of some service method. Then...
        return Request.CreateResponse(HttpStatusCode.Accepted);
    }
    return Request.CreateResponse(HttpStatusCode.BadRequest);
}

[HttpGet]
public HttpResponseMessage Get(int id)
{
    var myObjectResponse = GetObjectFromDb(id);
    // In your case, this will be result of some service method. Then...
    if(myObjectResponse == null)
        return Request.CreateResponse(HttpStatusCode.NotFound);

    return Request.CreateResponse(HttpStatusCode.OK, myObjectResponse);            
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,客户端可以只查看状态代码并决定如何处理响应,而无需实际尝试对其进行反序列化.您可以在此MSDN文章中获取有关HttpStatusCodes的更多信息.

他们添加了更多方法,例如ApiController.OkWebApi2.有关更多信息,您可以查看此ASP.NET WEB API概述页面.


TGH*_*TGH 0

是的,这作为 api 签名完全没问题