Web API操作返回类型的最佳实践 [英] Web API Action return type best practise

查看:43
本文介绍了Web API操作返回类型的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从此来源: http://www.tutorialsteacher.com/webapi/action-method-return-type-in​​-web-api 我知道,Web API中的Action可以返回:

From this source: http://www.tutorialsteacher.com/webapi/action-method-return-type-in-web-api I got, that Action in Web API can return:

  1. void
  2. 原始类型或复杂类型
  3. HttpResponseMessage
  4. IHttpActionResult

我知道每个选项的作用,但是我很好奇是否存在一些最佳实践,例如,始终使用IHttpActionResult作为返回类型,因为它是所有其他选项的超集.

I know what each of this options does, but I am curious whether there is some best practise, for example always use IHttpActionResult as return type, because it is a superset of all other options.

推荐答案

我使用 asp.net core ,但原理是相同的.另外,并不是说这是最好的方法,但对我来说,这是一个非常不错的设置.

I use asp.net core but principle is the same. Also, not saying this is the best way, but for me this is the setup that works pretty nice.

我总是使用 IActionResult 作为最灵活的方法.然后,我可以使用完全不知道我的服务(该操作方法称为)返回的 DTO 的操作方法.我所做的或多或少是这样的:

I always use IActionResult as its most flexible for me. I can then have action methods completely unaware of DTOs that my services (which action methods call) return. All i do is, more or less, something like this:

[CustomExceptionsFilter]
[CustomValidateModelFilter]
[Authorize(Roles="whatever")]
public IActionResult ActionMethod(params){
  return Ok(this._myService.whatever());
}

这样,如果您更改了服务返回的 DTO (这种情况经常发生,尤其是在早期开发阶段),那么我根本就不需要触摸控制器.

This way, if you change DTO that your service returns (which happens alot, especially in early development phases), i don' thave to touch my controller at all.

此外,在返回自定义异常错误过滤器捕获所有服务层自定义异常(例如验证异常,操作异常等)的地方,我有非常统一的返回方式.

Also, i have pretty much unified way of returning things where my custom exception error filter catches all service layer custom exceptions like validation exception, operation exception, etc...

[UPDATE]

在过滤器中,您实际上并没有返回传统意义上的结果.您宁可设置您的 context.result (类型为 IActionResult ).因此,可以说我的服务抛出了我的自定义 MyServiceOperationException(您不能这样做")异常.

in filters you don't actually return in a traditional sense. You rather set your context.result (which is of type IActionResult). So, lets say my service throws my custom MyServiceOperationException("You cannot do that") exception.

我在异常过滤器中所做的是:

What i do in my exception filter is:

public override void OnException(ExceptionContext context)
    {
      if (context.Exception is MyServiceOperationException)
      {
        context.Result = new BadRequestObjectResult(new MyErrorResult(){ 
          Message = context.Exception.Message,
          Code=context.Exception.MyErrorCode }
          );
      }
}

这篇关于Web API操作返回类型的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆