// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNet.Mvc.Core; using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.Mvc { /// /// An that returns a Created (201) response with a Location header. /// public class CreatedAtRouteResult : 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 CreatedAtRouteResult(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 CreatedAtRouteResult(string routeName, object routeValues, object value) : base(value) { RouteName = routeName; RouteValues = TypeHelper.ObjectToDictionary(routeValues); StatusCode = 201; } /// /// Gets or sets the used to generate URLs. /// public IUrlHelper UrlHelper { get; set; } /// /// Gets the name of the route to use for generating the URL. /// public string RouteName { get; private set; } /// /// Gets the route data to use for generating the URL. /// public IDictionary RouteValues { get; private set; } /// protected override void OnFormatting([NotNull] ActionContext context) { var request = context.HttpContext.Request; var urlHelper = UrlHelper ?? context.HttpContext.RequestServices.GetRequiredService(); var url = urlHelper.RouteUrl(RouteName, RouteValues, request.Scheme, request.Host.ToUriComponent()); if (string.IsNullOrEmpty(url)) { throw new InvalidOperationException(Resources.NoRoutesMatched); } context.HttpContext.Response.Headers.Set("Location", url); } } }