// 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.Collections.Generic; using System.Diagnostics.Contracts; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace System.Web.Http.Results { /// /// Represents an action result that returns an response. /// public class UnauthorizedResult : IHttpActionResult { private readonly IEnumerable _challenges; private readonly StatusCodeResult.IDependencyProvider _dependencies; /// Initializes a new instance of the class. /// The WWW-Authenticate challenges. /// The request message which led to this result. public UnauthorizedResult(IEnumerable challenges, HttpRequestMessage request) : this(challenges, new StatusCodeResult.DirectDependencyProvider(request)) { } /// Initializes a new instance of the class. /// The WWW-Authenticate challenges. /// The controller from which to obtain the dependencies needed for execution. public UnauthorizedResult(IEnumerable challenges, ApiController controller) : this(challenges, new StatusCodeResult.ApiControllerDependencyProvider(controller)) { } private UnauthorizedResult(IEnumerable challenges, StatusCodeResult.IDependencyProvider dependencies) { if (challenges == null) { throw new ArgumentNullException("challenges"); } Contract.Assert(dependencies != null); _challenges = challenges; _dependencies = dependencies; } /// Gets the WWW-Authenticate challenges. public IEnumerable Challenges { get { return _challenges; } } /// Gets the request message which led to this result. public HttpRequestMessage Request { get { return _dependencies.Request; } } /// public virtual Task ExecuteAsync(CancellationToken cancellationToken) { return Task.FromResult(Execute()); } private HttpResponseMessage Execute() { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); try { foreach (AuthenticationHeaderValue challenge in _challenges) { response.Headers.WwwAuthenticate.Add(challenge); } response.RequestMessage = _dependencies.Request; } catch { response.Dispose(); throw; } return response; } } }