asp.net-mvc – 在REST Web API调用中返回复杂对象
发布时间:2020-12-16 04:35:24 所属栏目:asp.Net 来源:网络整理
导读:我有一个Web API POST方法,它将自定义复杂对象MyObjectRequest作为参数排除,并返回自定义复杂对象MyObjectResponse. MyObjectResponse对象具有自定义复杂对象Token作为属性. public class MyObjectRequest{ public string AppName { get; set; } public stri
我有一个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; } } 我有Web API控制器,当用户进行HTTP POST调用时,我想返回MyObjectResponse. public class MyCustomController : Controller { public MyObjectResponse Post([FromBody] MyObjectRequest request) { //do my work here } } 这是制作MyCustomController API签名的正确方法吗? 解决方法
你有什么可以工作的.我倾向于将这些对象包装在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 and 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 and 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 and then if(myObjectResponse == null) return Request.CreateResponse(HttpStatusCode.NotFound); return Request.CreateResponse(HttpStatusCode.OK,myObjectResponse); } 通过这种方式,客户端可以查看状态代码并决定如何处理响应,而无需实际尝试反序列化它.您可以在this MSDN article获得有关HttpStatusCodes的更多信息. 他们在WebApi2中添加了更多方法,如ApiController.Ok.有关详细信息,请查看此ASP.NET WEB API overview page (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – 实际文化是否与SQL相关联到CLR float-double转换
- asp.net – 如何隐藏程序使用的技术?
- Asp.net mvc 知多少(四)
- asp.net – 使用[WebMethod]转义的JSON响应
- .Net Linq与Lambda表达式中GroupBy以多个字段分组
- 在ASP.NET属性中组合字符串
- asp.net-mvc-3 – Ninject和OnePerRequestModule
- asp.net-web-api – 如何配置Web API 2和结构图
- DxPackNet 5.视频高质量的压缩和传输
- asp.net-mvc – 缺少webpages_UsersInRoles
推荐文章
站长推荐
热点阅读