“.NET Return Context.Result bez dodatkowych nowych obiektów” Kod odpowiedzi

.NET Return Context.Result bez dodatkowych nowych obiektów

public class ErrorModel
{
    public string Error { get; set; }

    public int Id { get; set; }

    public List<int> Values { get; set; }
}

//filter

var error = new ErrorModel
{
    Error = context.Exception.Message,
    Id = 1,
    Values = new List<int> { 1, 2, 3 }
};
context.Result = new ObjectResult(error)
{
    StatusCode = 500
};
DreamCoder

.NET Return Context.Result bez dodatkowych nowych obiektów

//handles only exceptions caused by dividing by zero
public class DivideByZeroExceptionFilterAttribute : Attribute, IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        //chech if this is divide by zero exception
        if (!(context.Exception is DivideByZeroException))
            return;

        var myerror = new
        {
            result = false,
            message = "Division by zero went wrong"
        };
        context.Result = new ObjectResult(myerror)
        {
            StatusCode = 500
        };

        //set "handled" to true since exception is already property handled
        //and there is no need to run other filters
        context.ExceptionHandled = true;
    }
}
DreamCoder

Odpowiedzi podobne do “.NET Return Context.Result bez dodatkowych nowych obiektów”

Pytania podobne do “.NET Return Context.Result bez dodatkowych nowych obiektów”

Więcej pokrewnych odpowiedzi na “.NET Return Context.Result bez dodatkowych nowych obiektów” w C#

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu