I am facing an issue while making changes to the database using httpclient.putasync. following is the error message i receive : error while copying content to a stream
Any help would be great
namespace ABC
{
public enum SupportedHttpMethods
{
GET,
POST,
PUT,
DELETE
}
public class HttpClass : IHttpClass
{
Uri _uri;
HttpMethod _httpMethod;
StringContent _content;
HttpClient _httpClient = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true, AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip});
Action _action;
HttpResponseMessage _httpResponseMessage;
public HttpClass(
SupportedHttpMethods httpMethod,
string uri,
string content)
: this(httpMethod, uri)
{
if (httpMethod == SupportedHttpMethods.POST || httpMethod == SupportedHttpMethods.PUT)
{
JObject.Parse(content);
_content = new StringContent(content);
_content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
else
{
throw new InvalidHttpMethodContentCombinationException();
}
}
public HttpClass(
SupportedHttpMethods httpMethod,
string uri)
{
_uri = new Uri(uri);
_httpMethod = new HttpMethod(httpMethod.ToString());
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json")
);
switch (httpMethod)
{
case SupportedHttpMethods.GET:
_action = get;
break;
case SupportedHttpMethods.POST:
_action = post;
break;
case SupportedHttpMethods.PUT:
_action = put;
break;
case SupportedHttpMethods.DELETE:
_action = delete;
break;
default:
throw new InvalidHttpMethodException();
}
}
public HttpResponseMessage GetHttpResponseMessage()
{
return _httpResponseMessage;
}
public string GetResponseContent()
{
if (_httpMethod.Method == SupportedHttpMethods.GET.ToString())
return _httpResponseMessage.Content.ReadAsStringAsync().Result;
return null;
}
public void Invoke()
{
_action.Invoke();
}
void delete()
{
_httpResponseMessage = _httpClient.DeleteAsync(_uri).Result;
}
void get()
{
_httpResponseMessage = _httpClient.GetAsync(_uri).Result;
}
void post()
{
_httpResponseMessage = _httpClient.PostAsync(_uri, _content).Result;
}
void put()
{
_httpResponseMessage = _httpClient.PutAsync(_uri, _content).Result;
}
}
public class InvalidHttpMethodContentCombinationException : Exception
{
public InvalidHttpMethodContentCombinationException()
: base("When speciying content, either a POST or PUT must be used") { }
}
public class InvalidHttpMethodException : Exception
{
public InvalidHttpMethodException()
: base("Only PUT, POST, GET and DELETE Methods are supported") { }
}
}
Related
I am trying to capture the exception when the route is not found and wrap the exception with the generic response model.
I tried to implement, as given in the answer to the question, but this solution also doesn't seem to work in my use case.
Because the status code 404 is also added to the response when the resource is not found, like when Id is not found.
app.UseStatusCodePages(new StatusCodePagesOptions()
{
HandleAsync = (ctx) =>
{
if (ctx.HttpContext.Response.StatusCode == 404)
{
throw new RouteNotFoundException("Route not found");
}
return Task.FromResult(0);
}
})
RouteNotFoundException
public class RouteNotFoundException : Exception
{
public RouteNotFoundException()
: base()
{
}
public RouteNotFoundException(string message)
: base(message)
{
}
}
ApiExceptionFilterAttribute
public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IDictionary<Type, Action<ExceptionContext>> _exceptionHandlers;
public ApiExceptionFilterAttribute()
{
// Register known exception types and handlers.
_exceptionHandlers = new Dictionary<Type, Action<ExceptionContext>>
{
{ typeof(RouteNotFoundException), HandleNotFoundException }
};
}
public override void OnException(ExceptionContext context)
{
HandleException(context);
base.OnException(context);
}
private void HandleException(ExceptionContext context)
{
Type type = context.Exception.GetType();
if (_exceptionHandlers.ContainsKey(type))
{
_exceptionHandlers[type].Invoke(context);
return;
}
HandleUnknownException(context);
}
private void HandleNotFoundException(ExceptionContext context)
{
var exception = context.Exception as RouteNotFoundException;
var details = new ProblemDetails()
{
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4",
Title = "The specified resource was not found.",
Detail = exception.Message
};
context.Result = new NotFoundObjectResult(details);
context.ExceptionHandled = true;
}
private void HandleUnknownException(ExceptionContext context)
{
var details = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An error occurred while processing your request.",
Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1"
};
context.Result = new ObjectResult(details)
{
StatusCode = StatusCodes.Status500InternalServerError
};
context.ExceptionHandled = true;
}
}
ResponseWrapperMiddleware
public class ResponseWrapperMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ResponseWrapperMiddleware> _logger;
public ResponseWrapperMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = loggerFactory?.CreateLogger<ResponseWrapperMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory));
}
public async Task Invoke(HttpContext httpContext)
{
try
{
var currentBody = httpContext.Response.Body;
using (var memoryStream = new MemoryStream())
{
//set the current response to the memorystream.
httpContext.Response.Body = memoryStream;
await _next(httpContext);
//reset the body
httpContext.Response.Body = currentBody;
memoryStream.Seek(0, SeekOrigin.Begin);
var readToEnd = new StreamReader(memoryStream).ReadToEnd();
var objResult = JsonConvert.DeserializeObject(readToEnd);
var result = CommonApiResponse.Create((HttpStatusCode)httpContext.Response.StatusCode, objResult, null);
await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(result));
}
}
catch (Exception ex)
{
if (httpContext.Response.HasStarted)
{
_logger.LogWarning("The response has already started, the http status code middleware will not be executed.");
throw;
}
return;
}
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class ResponseWrapperMiddlewareExtensions
{
public static IApplicationBuilder UseResponseWrapperMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ResponseWrapperMiddleware>();
}
}
Generic Response Model
public class CommonApiResponse
{
public static CommonApiResponse Create(HttpStatusCode statusCode, object result = null, string errorMessage = null)
{
return new CommonApiResponse(statusCode, result, errorMessage);
}
public string Version => "1.2.3";
public int StatusCode { get; set; }
public string RequestId { get; }
public string ErrorMessage { get; set; }
public object Result { get; set; }
protected CommonApiResponse(HttpStatusCode statusCode, object result = null, string errorMessage = null)
{
RequestId = Guid.NewGuid().ToString();
StatusCode = (int)statusCode;
Result = result;
ErrorMessage = errorMessage;
}
}
How to handle the error if the route is not found and capture the error in the generic model? What is the workaround for this case?
i dont know where i am missing i am stuck to send error message if the user name and password is wrong. my service is working well i can able to send the error message manually if user id and password is not match with 200 status and manually created status with success. here is my code i have created the HandleRequest class
public class HandleRequest : Attribute, IAuthenticationFilter
{
public string Realm { get; set; }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
//throw new NotImplementedException();
HttpRequestMessage request = context.Request;
AuthenticationHeaderValue authorization = request.Headers.Authorization;
string status = await SendAsync(request, cancellationToken);
if (context.Request.RequestUri.LocalPath == "/Login/UserLogin")
{
return;
}
else if (authorization == null)
{
// No authentication was attempted (for this authentication method).
// Do not set either Principal (which would indicate success) or ErrorResult (indicating an error).
context.ErrorResult = new AuthenticationFailureResult("Null auth token..", request);
return;
}
else if (status == "Success")
{
return;
}
else
{
context.ErrorResult = new AuthenticationFailureResult("Invalid auth token..", request);
return;
}
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
Challenge(context);
return Task.FromResult(0);
}
private void Challenge(HttpAuthenticationChallengeContext context)
{
string parameter;
if (String.IsNullOrEmpty(Realm))
{
parameter = null;
}
else
{
// A correct implementation should verify that Realm does not contain a quote character unless properly
// escaped (precededed by a backslash that is not itself escaped).
parameter = "realm=\"" + Realm + "\"";
}
context.ChallengeWith("Basic", parameter);
}
public virtual bool AllowMultiple
{
get { return false; }
}
private static bool TryRetrieveToken(HttpRequestMessage request, out string token)
{
token = null;
IEnumerable<string> authzHeaders;
if (!request.Headers.TryGetValues("Authorization", out authzHeaders) || authzHeaders.Count() > 1)
{
return false;
}
var bearerToken = authzHeaders.ElementAt(0);
token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
return true;
}
public async Task<string> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
string status = "";
HttpStatusCode statusCode;
string token;
//determine whether a jwt exists or not
if (!TryRetrieveToken(request, out token))
{
statusCode = HttpStatusCode.Unauthorized;
//allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute
//return base.SendAsync(request, cancellationToken);
}
try
{
string sec = WebConfigurationManager.AppSettings["sec"];
var now = DateTime.UtcNow;
var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
SecurityToken securityToken;
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
TokenValidationParameters validationParameters = new TokenValidationParameters()
{
ValidAudience = "http://localhost:1987",
ValidIssuer = "http://localhost:1987",
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
LifetimeValidator = this.LifetimeValidator,
IssuerSigningKey = securityKey
};
//extract and assign the user of the jwt
Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken);
HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken);
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var id = int.Parse(identity.Claims.Where(c => c.Type == "id")
.Select(c => c.Value).SingleOrDefault());
bool isValidToken = IsValidToken(id, userName, type);
if (isValidToken == true)
{
status = "Success";
}
else
{
statusCode = HttpStatusCode.Unauthorized;
status = "Unauthorized";
}
}
catch (SecurityTokenValidationException e)
{
e.Message.ToString();
statusCode = HttpStatusCode.Unauthorized;
status = "Unauthorized";
}
catch (Exception ex)
{
ex.Message.ToString();
statusCode = HttpStatusCode.InternalServerError;
status = "InternalServerError";
}
return status;
}
public bool LifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
{
if (expires != null)
{
if (DateTime.UtcNow < expires) return true;
}
return false;
}
private bool IsValidToken(int? id, string userName, string type)
{
bool isValid = false;
using (MCSDEMOEntities con = new MCSDEMOEntities())
{
var GetUserDatails = (from u in con.ios_Users
where u.ID == id && u.LOGIN == userName && u.TYPEDESCR == type
select u).ToList();
if (GetUserDatails.Count == 1)
{
isValid = true;
}
else
{
isValid = false;
}
}
return isValid;
}
}
public static class HttpRequestHeadersExtensions
{
public static void Set(this HttpRequestHeaders headers, string name, string value)
{
if (headers.Contains(name)) headers.Remove(name);
headers.Add(name, value);
}
}
public static class HttpAuthenticationChallengeContextExtensions
{
public static void ChallengeWith(this HttpAuthenticationChallengeContext context, string scheme)
{
ChallengeWith(context, new AuthenticationHeaderValue(scheme));
}
public static void ChallengeWith(this HttpAuthenticationChallengeContext context, string scheme, string parameter)
{
ChallengeWith(context, new AuthenticationHeaderValue(scheme, parameter));
}
public static void ChallengeWith(this HttpAuthenticationChallengeContext context, AuthenticationHeaderValue challenge)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
context.Result = new AddChallengeOnUnauthorizedResult(challenge, context.Result);
}
}
public class AddChallengeOnUnauthorizedResult : IHttpActionResult
{
public AuthenticationHeaderValue Challenge { get; private set; }
public IHttpActionResult InnerHttpResult { get; private set; }
public AddChallengeOnUnauthorizedResult(AuthenticationHeaderValue challenge, IHttpActionResult innerResult)
{
Challenge = challenge;
InnerHttpResult = innerResult;
}
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = await InnerHttpResult.ExecuteAsync(cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
// Only add one challenge per authentication scheme.
if (!response.Headers.WwwAuthenticate.Any((h) => h.Scheme == Challenge.Scheme))
{
response.Headers.WwwAuthenticate.Add(Challenge);
}
}
return response;
}
}
public class AuthenticationFailureResult : IHttpActionResult
{
public string ReasonPhrase { get; private set; }
public HttpRequestMessage Request { get; private set; }
public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request)
{
ReasonPhrase = reasonPhrase;
Request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(execute());
}
private HttpResponseMessage execute()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
response.RequestMessage = Request;
response.ReasonPhrase = ReasonPhrase;
return response;
}
}
my webapi config file
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
//check each request
config.Filters.Add(new HandleRequest());
// configuration for json reponse
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
//LoginController
// Login Model
config.Routes.MapHttpRoute(
name: "LoginApi",
routeTemplate: "{controller}/{action}",
defaults: new { controller = "Login", action = "UserLogin", id = RouteParameter.Optional }
);
}
and my login controller
public class LoginController : ApiController
{
LoginModel logMod = new LoginModel();
LoginResponse logResp = new LoginResponse();
[HttpPost]
public LoginResponse UserLogin(LoginRequest logReq)
{
logResp = logMod.UserLogin(logReq );
return logResp;
}
}
login model class
public LoginResponse UserLogin(LoginRequest LogReq)
{
LoginResponse logResp = new LoginResponse();
try
{
if (LogReq.userName != "" && LogReq.password != "")
{
using (MCSDEMOEntities DataModel = new MCSDEMOEntities())
{
var UserDetails = (from user in DataModel.ios_Users
where (user.LOGIN == LogReq.userName && user.PASSWORD == LogReq.password && user.ACTIVE != 0)
select new
{
user.ID,
user.TYPEDESCR,
user.USERNAME
}).ToList();
if (UserDetails.Count != 0)
{
foreach (var Udetails in UserDetails)
{
logResp.id = Udetails.ID;
logResp.type = Udetails.TYPEDESCR;
logResp.userName = Udetails.USERNAME;
}
//create jwt token.
logResp.userToken = createToken(logResp.id, logResp.type, LogReq.userName);
logResp.Status = "Success";
}
else
{
logResp.Status = "401";
//throw new HttpResponseException("Customer Name cannot be empty", HttpStatusCode.BadRequest);
// throw new AuthenticationFailureResult("","")
}
}
}
else
{
logResp.Status = "No Condition Match";
}
}
catch (Exception ex)
{
logResp.Status = ex.Message.ToString();
}
return logResp;
}
in above code it excecute service well but even if user id and password doesn't matches it send http- 200 ok message with my status - 401 in json. i want to pass http with code 401
You need to return HttpResponseMessage from your api so that you can wrap your response object with the other information like status
[HttpPost]
public HttpResponseMessage UserLogin(LoginRequest logReq)
{
logResp = logMod.UserLogin(logReq );
// Decide based on your logic. This is
// a mock example.
var status = HttpStatusCode.OK
return Request.CreateResponse(HttpStatusCode.OK, logResp);
}
You can find more information here: https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results
Quoting from it:
HttpResponseMessage Convert directly to an HTTP response
Other type Write the serialized return value into the response body; return 200 (OK).
I have 2 viewmodel, aviewmodel and bviewmodel. in aviewmodel and bviewmodel are used method GetListEmployees(). i have a problem.
In aviewmodel,I have successfully run the GetListEmployees().but in bviewmodel then it does not work. I debug and I see it was thrown when it came to response. I don't know why it's like that.
video description. https://youtu.be/CD3lHKx3igs
Function to get the list.
async private Task GetListEmployees()
{
var result = await GeneralMethods.Ins.GetDataFromDB<Employee>("Employee/employees");
// ListEmployee = new ObservableCollection<Employee>(result);
}
This is class read api.
public class GeneralMethods
{
private static GeneralMethods _Ins;
public static GeneralMethods Ins
{
get
{
if (_Ins == null)
_Ins = new GeneralMethods();
return GeneralMethods._Ins;
}
private set
{
GeneralMethods._Ins = value;
}
}
public async Task<List<T>> GetDataFromDB<T>(string urlDB)
{
string url = "http://webapi.local/api/" + urlDB;
using (HttpResponseMessage response = await APIHelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsAsync<List<T>>().Result;
return result;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
APIHelper
public static class APIHelper
{
public static HttpClient ApiClient { get; set; }
public static void InitializeClient()
{
ApiClient = new HttpClient();
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
I have code like this:
public class Paket
{
public int PaketID { get { return _PaketID; } set { _PaketID = value; } }
public int ProizvodID { get { return _ProizvodID; } set { _ProizvodID = value; } }
public double Kolicina { get { return _Kolicina; } set { _Kolicina = value; } }
public double CenaBezPdv { get { return _CenaBezPdv; } set { _CenaBezPdv = value; } }
private int _PaketID;
private int _ProizvodID;
private double _Kolicina;
private double _CenaBezPdv;
public string _errorMessage { get; set; }
private Paket()
{
}
public Paket(int proizvodID)
{
if (proizvodID == null) { throw new Exception("ProizvodID ne moze biti NULL!"); }
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string url = "https://www.new.termodom.rs/Php/Proizvodi/Paketi/GetOne.php?proizvodid=" + proizvodID;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
_errorMessage = "Paket nije pronadjen u web bazi!";
break;
default:
Paket p = JsonConvert.DeserializeObject<Paket>(resp);
this._PaketID = p.PaketID;
this._ProizvodID = p.ProizvodID;
this._Kolicina = p.Kolicina;
this._CenaBezPdv = p.CenaBezPdv;
break;
}
}
public static List<Paket> SviPaketi(int ProizvodID)
{
List<Paket> list = new List<Paket>();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string url = "https://www.new.termodom.rs/Php/Proizvodi/Paketi/GetAll.php?proizvodid=" + ProizvodID;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
break;
default:
list = JsonConvert.DeserializeObject<List<Paket>>(resp);
break;
}
return list;
}
}
When i run function like this List<Proizvod> myList = Proizvod.SviPaketi(139) i am getting some error (i do not know now which one it was but it is not important for my question).
When i started debugging i saw that JsonConvert.DeserializeObject<List<Paket>>(resp); doesn't enter only private Paket() which is empty but public Paket(int proizvodID) which has some code inside it.
So my question is why did JsonConvert.DeserializeObject<List<Paket>>(resp); triggered public Paket(int proizvodID) when i haven't passed any parameter to it?
JSON de-serializer will prefer a public constructor. You can however make it use the private constructor using a ConstructorHandling. Check this example
I've searched this intensive but can't get it to work.
I've haven an Web AP2 OData API and need to return a custom error class.
Here is what I have:
public class Error
{
public string Code { get; set; }
public string Message { get; set; }
}
In Global.asax.cs
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageInterceptor());
}
public class MessageInterceptor : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken).ContinueWith(
task =>
{
var body = task.Result.Content.ReadAsStringAsync().Result;
var resultObj = JsonConvert.DeserializeObject(body.Replace("value", "Results"));
task.Result.Content = new ObjectContent(typeof(object), resultObj, new JsonMediaTypeFormatter());
return task.Result;
}, cancellationToken);
}
}
In WebApiConfig,cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new HandleApiExceptionAttribute());
}
}
public class HandleApiExceptionAttribute : ExceptionFilterAttribute, IExceptionFilter
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is Error)
{
var res = context.Exception.Message;
//Define the Response Message
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(res),
ReasonPhrase = res
};
//Create the Error Response
context.Response = response;
}
}
public class OrdersController : ODataControllerA controller
{
private Context db = new Context();
// GET: odata/Orders
[Queryable]
public IQueryable<Orders> GetOrders(ODataQueryOptions<Orders> opts)
{
<some code producing error>
Error theError = new Error()
{
Code = "1000",
Message = "Geen filter gespecificeerd"
};
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, theError);
//return Request.CreateResponse(HttpStatusCode.BadRequest, theError);
throw new HttpResponseException(response);
}
When I try this this crashes in the MessageInterceptor.
This is there because a third party consuming the API want's it in the specific format.
When the code runs correct it returns results{}
On error it should return Error{code:, message: }
Anyone ideas?
Jeroen
This is what I came up with:
I changed the controller to:
[Queryable, BasicAuthentication]
public IHttpActionResult GetOrders(ODataQueryOptions<Orders> opts)
{
else
{
Error theError = new Error()
{
Code = "1000",
Message = "Geen filter gespecificeerd"
};
return new ErrorResult(theError, Request);
}
return Ok(resultList);
}
Using this class:
public class ErrorResult : IHttpActionResult
{
Error _error;
HttpRequestMessage _request;
public ErrorResult(Error error, HttpRequestMessage request)
{
_error = error;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
List<Error> _errorList = new List<Error>();
_errorList.Add(_error);
error err = new error()
{
errors = _errorList
};
var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new ObjectContent<error>(err, new JsonMediaTypeFormatter()),
RequestMessage = _request
};
return Task.FromResult(response);
}
}
public class Error
{
public string Code { get; set; }
public string Message { get; set; }
}
public class error
{
public List<Error> errors { get; set; }
}