// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Core; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.Mvc { /// /// An that returns a Accepted (202) response with a Location header. /// public class AcceptedAtRouteResult : ObjectResult { /// /// Initializes a new instance of the class with the values /// provided. /// /// The route data to use for generating the URL. /// The value to format in the entity body. public AcceptedAtRouteResult(object routeValues, object value) : this(routeName: null, routeValues: routeValues, value: value) { } /// /// Initializes a new instance of the class with the values /// provided. /// /// The name of the route to use for generating the URL. /// The route data to use for generating the URL. /// The value to format in the entity body. public AcceptedAtRouteResult( string routeName, object routeValues, object value) : base(value) { RouteName = routeName; RouteValues = routeValues == null ? null : new RouteValueDictionary(routeValues); StatusCode = StatusCodes.Status202Accepted; } /// /// Gets or sets the used to generate URLs. /// public IUrlHelper UrlHelper { get; set; } /// /// Gets or sets the name of the route to use for generating the URL. /// public string RouteName { get; set; } /// /// Gets or sets the route data to use for generating the URL. /// public RouteValueDictionary RouteValues { get; set; } /// public override void OnFormatting(ActionContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } base.OnFormatting(context); var urlHelper = UrlHelper; if (urlHelper == null) { var services = context.HttpContext.RequestServices; urlHelper = services.GetRequiredService().GetUrlHelper(context); } var url = urlHelper.Link(RouteName, RouteValues); if (string.IsNullOrEmpty(url)) { throw new InvalidOperationException(Resources.NoRoutesMatched); } context.HttpContext.Response.Headers[HeaderNames.Location] = url; } } }