// 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.Formatting;
using System.Threading;
using System.Threading.Tasks;
namespace System.Web.Http.Results
{
///
/// Represents an action result that returns a response and performs
/// content negotiation on an with a .
///
public class BadRequestErrorMessageResult : IHttpActionResult
{
private readonly string _message;
private readonly NegotiatedContentResult.IDependencyProvider _dependencies;
/// Initializes a new instance of the class.
/// The user-visible error message.
/// The content negotiator to handle content negotiation.
/// The request message which led to this result.
/// The formatters to use to negotiate and format the content.
public BadRequestErrorMessageResult(string message, IContentNegotiator contentNegotiator,
HttpRequestMessage request, IEnumerable formatters)
: this(message, new NegotiatedContentResult.DirectDependencyProvider(contentNegotiator, request,
formatters))
{
}
/// Initializes a new instance of the class.
/// The user-visible error message.
/// The controller from which to obtain the dependencies needed for execution.
public BadRequestErrorMessageResult(string message, ApiController controller)
: this(message, new NegotiatedContentResult.ApiControllerDependencyProvider(controller))
{
}
private BadRequestErrorMessageResult(string message,
NegotiatedContentResult.IDependencyProvider dependencies)
{
if (message == null)
{
throw new ArgumentNullException("message");
}
Contract.Assert(dependencies != null);
_message = message;
_dependencies = dependencies;
}
/// Gets the user-visible error message.
public string Message
{
get { return _message; }
}
/// Gets the content negotiator to handle content negotiation.
public IContentNegotiator ContentNegotiator
{
get { return _dependencies.ContentNegotiator; }
}
/// Gets the request message which led to this result.
public HttpRequestMessage Request
{
get { return _dependencies.Request; }
}
/// Gets the formatters to use to negotiate and format the content.
public IEnumerable Formatters
{
get { return _dependencies.Formatters; }
}
///
public virtual Task ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(Execute());
}
private HttpResponseMessage Execute()
{
HttpError error = new HttpError(_message);
return NegotiatedContentResult.Execute(HttpStatusCode.BadRequest, error,
_dependencies.ContentNegotiator, _dependencies.Request, _dependencies.Formatters);
}
}
}