// 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.Infrastructure; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.Mvc { /// /// An that returns a Created (201) response with a Location header. /// [DefaultStatusCode(DefaultStatusCode)] public class CreatedResult : ObjectResult { private const int DefaultStatusCode = StatusCodes.Status201Created; private string _location; /// /// Initializes a new instance of the class with the values /// provided. /// /// The location at which the content has been created. /// The value to format in the entity body. public CreatedResult(string location, object value) : base(value) { if (location == null) { throw new ArgumentNullException(nameof(location)); } Location = location; StatusCode = DefaultStatusCode; } /// /// Initializes a new instance of the class with the values /// provided. /// /// The location at which the content has been created. /// The value to format in the entity body. public CreatedResult(Uri location, object value) : base(value) { if (location == null) { throw new ArgumentNullException(nameof(location)); } if (location.IsAbsoluteUri) { Location = location.AbsoluteUri; } else { Location = location.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped); } StatusCode = DefaultStatusCode; } /// /// Gets or sets the location at which the content has been created. /// public string Location { get => _location; set { if (value == null) { throw new ArgumentNullException(nameof(value)); } _location = value; } } /// public override void OnFormatting(ActionContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } base.OnFormatting(context); context.HttpContext.Response.Headers[HeaderNames.Location] = Location; } } }