ASP.NET Core处理Web API中的自定义响应/输出格式的方法 [英] ASP.NET Core ways to handle custom response/output format in Web API

查看:656
本文介绍了ASP.NET Core处理Web API中的自定义响应/输出格式的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建自定义JSON格式,该格式将响应包装在数据中并返回Content-Type,如

I'd like to create custom JSON format, that would wrap the response in data and would return Content-Type like

vnd.myapi + json

vnd.myapi+json

当前,我创建了一个包装类,将其返回到控制器中,但是如果可以在后台进行处理,那就更好了:

Currently I have created like a wrapper classes that I return in my controllers but it would be nicer if that could be handled under the hood:

public class ApiResult<TValue>
{
    [JsonProperty("data")]
    public TValue Value { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> Metadata { get; } = new Dictionary<string, object>();

    public ApiResult(TValue value)
    {
        Value = value;
    }
}

[HttpGet("{id}")]
public async Task<ActionResult<ApiResult<Bike>>> GetByIdAsync(int id)
{
    var bike = _dbContext.Bikes.AsNoTracking().SingleOrDefault(e => e.Id == id);
    if (bike == null)
    {
        return NotFound();
    }
    return new ApiResult(bike);
}

public static class ApiResultExtensions
{
    public static ApiResult<T> AddMetadata<T>(this ApiResult<T> result, string key, object value)
    {
        result.Metadata[key] = value;
        return result;
    }
}

我想返回以下响应:

{
    "data": { ... },
    "pagination": { ... },
    "someothermetadata": { ... }
}

但是在我的控制器的操作中,必须以某种方式将分页添加到元数据中,当然,这里有一些有关内容协商的文章:

But the pagination would have to be added somehow to the metadata in my controller's action, of course there's some article about content negotiation here: https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1 but still I'd like to be sure I'm on the right track.

如果要使用我的自定义格式化程序在后台进行处理,那我将如何向其中添加像分页一样的元数据,而不是数据"而不是它的内部?

If that would be handled under the hood with my custom formatter then how would I add metadata like a pagination to it, to be aside of "data" and not inside of it?

使用自定义格式化程序时,我仍然希望通过某种方式或通过某种机制向其添加元数据,以便该格式可以扩展.

When having a custom formatter I'd like to still have some way to add metadata to it from my controllers or by some mechanism so the format could be extensible.

上述方法的优点或缺点是,它可与所有序列化器xml,json,yaml等一起使用.通过具有自定义格式化程序,它可能仅适用于json,而我将需要创建一些不同的格式化程序来支持所有我想要的格式.

One advantage or disadvantage with the approach above is that it works with all serializers xml, json, yaml etc. By having custom formatter it would probably work only for json, and I will need to create few different formatters to support all the formats that I want.

推荐答案

好的,在花费大量时间使用ASP.NET Core之后,基本上可以想到4种方法来解决此问题.老实说,该主题本身非常复杂且涉及面广,我认为这没有灵丹妙药或最佳实践.

Okay, after spending some good amount of time with ASP.NET Core there are basically 4 ways I can think of to solve this. The topic itself is quite complex and broad to think of and honestly, I don't think there's a silver bullet or the best practice for this.

对于自定义Content-Type(假设您要实现application/hal+json),官方方法(也许也是最优雅的方法)是创建

For custom Content-Type(let's say you want to implement application/hal+json), the official way and probably the most elegant way is to create custom output formatter. This way your actions won't know anything about the output format but you still can control the formatting behaviour inside your controllers thanks to dependency injection mechanism and scoped lifetime.

这是 OData官方使用的最流行的方式C#库用于ASP.Net Core的json:api框架.可能是实现超媒体格式的最佳方法.

This is the most popular way used by OData official C# libraries and json:api framework for ASP.Net Core. Probably the best way to implement hypermedia formats.

要从控制器控制您的自定义输出格式器,您要么必须创建自己的上下文",要么在控制器和自定义格式化程序之间传递数据,并将其添加到具有范围有效期的DI容器中:

To control your custom output formatter from a controller you either have to create your own "context" to pass data between your controllers and custom formatter and add it to DI container with scoped lifetime:

services.AddScoped<ApiContext>();

这样,每个请求将只有一个ApiContext实例.您可以将其注入到控制器和输出格式化程序中,并在它们之间传递数据.

This way there will be only one instance of ApiContext per request. You can inject it to both you controllers and output formatters and pass data between them.

您还可以使用ActionContextAccessorHttpContextAccessor并在自定义输出格式化程序中访问控制器和操作.要访问控制器,必须将ActionContextAccessor.ActionContext.ActionDescriptor强制转换为ControllerActionDescriptor.然后,您可以使用IUrlHelper和操作名称在输出格式器内部生成链接,以便控制器摆脱这种逻辑.

You can also use ActionContextAccessor and HttpContextAccessor and access your controller and action inside your custom output formatter. To access controller you have to cast ActionContextAccessor.ActionContext.ActionDescriptor to ControllerActionDescriptor. You can then generate links inside your output formatters using IUrlHelper and action names so the controller will be free from this logic.

IActionContextAccessor是可选的,默认情况下不会添加到容器中,要在项目中使用它,必须将其添加到IoC容器中.

IActionContextAccessor is optional and not added to the container by default, to use it in your project you have to add it to the IoC container.

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>()

在自定义输出格式化程序中使用服务:

您不能在formatter类中进行构造函数依赖项注入.例如,您无法通过将logger参数添加到构造函数来获取logger.要访问服务,您必须使用传递到您的方法中的上下文对象.

You can't do constructor dependency injection in a formatter class. For example, you can't get a logger by adding a logger parameter to the constructor. To access services, you have to use the context object that gets passed in to your methods.

Swashbuckle支持:

Swashbuckle显然不会使用这种方法和带有过滤器的方法生成正确的响应示例.您可能必须创建自定义文档过滤器.

Swashbuckle obviously won't generate a correct response example with this approach and the approach with filters. You will probably have to create your custom document filter.

示例:如何添加分页链接:

通常,分页,过滤使用规范模式解决,您通常会对该规范使用一些通用模型在您的[Get]动作中.然后,您可以在格式化程序中确定当前执行的操作是否按其参数类型或其他方式返回元素列表:

Usually paging, filtering is solved with specification pattern you will typically have some common model for the specification in your [Get] actions. You can then identify in your formatter if currently executed action is returning list of elements by it's parameter type or something else:

var specificationParameter = actionContextAccessor.ActionContext.ActionDescriptor.Parameters.SingleOrDefault(p => p.ParameterType == typeof(ISpecification<>));
if (specificationParameter != null)
{
   // add pagination links or whatever
   var urlHelper = new UrlHelper(actionContextAccessor.ActionContext);
   var link = urlHelper.Action(new UrlActionContext()
   {
       Protocol = httpContext.Request.Scheme,
       Host = httpContext.Request.Host.ToUriComponent(),
       Values = yourspecification
   })
}

优势(或没有优势):

  • 您的操作未定义格式,它们对格式或如何生成链接以及将链接放在何处一无所知.他们只知道结果类型,而不知道描述结果的元数据.

  • Your actions don't define the format, they know nothing about a format or how to generate links and where to put them. They know only of the result type, not the meta-data describing the result.

可重复使用,您可以轻松地将格式添加到其他项目中,而不必担心如何在操作中处理它.与链接,格式相关的所有内容均在后台进行处理.您的动作无需任何逻辑.

Re-usable, you can easily add the format to other projects without worrying how to handle it in your actions. Everything related to linking, formatting is handled under the hood. No need for any logic in your actions.

序列化实现由您决定,您不必使用Newtonsoft.JSON,可以使用

Serialization implementation is up to you, you don't have to use Newtonsoft.JSON, you can use Jil for example.

缺点:

  • 此方法的一个缺点是,它仅适用于特定的Content-Type.因此,为了支持XML,我们需要创建另一个具有Content-Type的自定义输出格式器,例如vnd.myapi+xml而不是vnd.myapi+json.

我们不直接处理动作结果

We're not working directly with the action result

实施起来可能会更复杂

结果过滤器使我们能够定义某种行为,这些行为将在我们的操作返回之前执行.我认为这是某种形式的挂机.我认为这不是包装我们的回复的正确位置.

Result filters allow us to define some kind of behaviour that will execute before our action returns. I think of it as some form of post-hook. I don't think it's the right place for wrapping our response.

它们可以应用于每个动作,也可以全局应用于所有动作.

They can be applied per action or globally to all actions.

我个人不会将其用于此类事情,而是将其用作第三个选项的补充.

Personally, I wouldn't use it for this kind of thing but use it as a supplement for the 3rd option.

包装输出的样本结果过滤器:

Sample result filter wrapping the output:

public class ResultFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.Result is ObjectResult objectResult)
        {
            objectResult.Value = new ApiResult { Data = objectResult.Value };
        }
    }

    public void OnResultExecuted(ResultExecutedContext context)
    {
    }
}

您可以在IActionFilter中添加相同的逻辑,它也应该工作:

You can put the same logic in IActionFilter and it should work as well:

public class ActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Result is ObjectResult objectResult)
        {
            objectResult.Value = new ApiResult { Data = objectResult.Value };
        }
    }
}

这是包装您的响应的最简单方法,特别是如果您已经具有带有控制器的现有项目.因此,如果您在乎时间,请选择此时间.

This is the easiest way to wrap your responses especially if you already have the existing project with controllers. So if you care about time, choose this one.

(我在问题中的处理方式)

(The way I do it in my question)

这里也使用了它: https://github.com/nbarbettini/BeautifulRestApi/tree/master/src 来实现 https://github. com/ionwg/ion-doc/blob/master/index.adoc 我个人认为这将更适合自定义输出格式化程序.

This is also used here: https://github.com/nbarbettini/BeautifulRestApi/tree/master/src to implement https://github.com/ionwg/ion-doc/blob/master/index.adoc personally I think this would be better suited in custom output formatter.

这可能是最简单的方法,但也可以密封".您的API会采用该特定格式.这种方法有很多优点,但也可能有一些缺点.例如,如果您想更改API的格式,那么就很难做到这一点,因为您的操作与该特定的响应模型结合在一起,并且如果您的操作中对该模型具有某种逻辑,例如,您可以重新为下一个和上一个添加分页链接.实际上,您必须重写所有操作和格式化逻辑以支持该新格式.使用自定义输出格式化程序,您甚至可以根据Content-Type标头支持两种格式.

This is probably the easiest way but it's also "sealing" your API to that specific format. There are advantages to this approach but there can be some disadvantages too. For example, if you wanted to change the format of your API, you can't do it easily because your actions are coupled with that specific response model, and if you have some logic on that model in your actions, for example, you're adding pagination links for next and prev. You practically have to rewrite all your actions and formatting logic to support that new format. With custom output formatter you can even support both formats depending on the Content-Type header.

优势:

  • 适用于所有Content-Type,格式是API不可或缺的一部分.
  • Swashbuckle可以直接使用,在使用ActionResult<T>(2.1+)时,您还可以在操作中添加[ProducesResponseType]属性.
  • Works with all Content-Types, the format is an integral part of your API.
  • Swashbuckle works out of the box, when using ActionResult<T> (2.1+), you can also add [ProducesResponseType] attribute to your actions.

缺点:

  • 您无法使用Content-Type标头控制格式.对于application/jsonapplication/xml,它始终保持相同. (也许是优势?)
  • 您的操作负责返回正确格式的响应. return new ApiResponse(obj);之类的东西,或者您可以创建扩展方法并像obj.ToResponse()这样调用它,但是您始终必须考虑正确的响应格式.
  • 从理论上讲,像vnd.myapi+json这样的自定义Content-Type并没有带来任何好处,并且仅仅为该名称实现自定义输出格式化程序是没有意义的,因为格式化仍然是控制器操作的责任.
  • You can't control the format with Content-Type header. It always remains the same for application/json and application/xml. (maybe it's advantage?)
  • Your actions are responsible for returning the correctly formatted response. Something like: return new ApiResponse(obj); or you can create extension method and call it like obj.ToResponse() but you always have to think about the correct response format.
  • Theoretically custom Content-Type like vnd.myapi+json doesn't give any benefit and implementing custom output formatter just for the name doesn't make sense as formatting is still responsibility of controller's actions.

我认为这更像是正确处理输出格式的快捷方式.我认为遵循单一责任原则,它应该是输出格式化程序的工作,正如名称建议的那样输出.

I think this is more like a shortcut for properly handling the output format. I think following the single responsibility principle it should be the job for output formatter as the name suggests it formats the output.

您可以做的最后一件事是自定义中间件,您可以在其中解析IActionResultExecutor并返回IActionResult,就像在MVC控制器中一样.

The last thing you can do is a custom middleware, you can resolve IActionResultExecutor from there and return IActionResult like you would do in your MVC controllers.

https://github.com/aspnet/Mvc/issues/7238# issuecomment-357391426

如果需要访问控制器信息,还可以解析IActionContextAccessor以访问MVC的动作上下文,并将ActionDescriptor强制转换为ControllerActionDescriptor.

You could also resolve IActionContextAccessor to get access to MVC's action context and cast ActionDescriptor to ControllerActionDescriptor if you need to access controller info.

医生说:

资源过滤器的工作方式类似于中间件,因为它们围绕管道中稍后出现的所有内容的执行.但是筛选器与中间件的不同之处在于它们是MVC的一部分,这意味着它们可以访问MVC上下文和构造.

Resource filters work like middleware in that they surround the execution of everything that comes later in the pipeline. But filters differ from middleware in that they're part of MVC, which means that they have access to MVC context and constructs.

但这并不是完全正确的,因为您可以访问操作上下文,并且可以从中间件返回操作结果,该结果是MVC的一部分.

But it's not entirely true, because you can access action context and you can return action results which is part of MVC from your middleware.

如果您要添加任何内容,请分享您自己的经验和优点或缺点.

If you have anything to add, share your own experiences and advantages or disadvantages feel free to comment.

这篇关于ASP.NET Core处理Web API中的自定义响应/输出格式的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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