Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
Почему был выбран JsonResult?
return success ? new JsonResult($"Update successful {document.Id}") : new JsonResult("Update was not successful")Т.е результат вроде бы 200 ОК, а вроде и нет.
Иногда сталкиваюсь с преимущественно старыми системами, которые возвращают ошибки с 200-м кодом ответа Http. Столько "радости" с ними интегрироваться.
В этом случае правильнее использовать наследников StatusCodeResult, например BadRequestResult,OkResult.
Тестирование
Что конкретно вы тестируете и зачем?
serviceMock.Object.Work();
serviceMock.Verify(x => x.Work()); public abstract class BaseModel
{
public Guid Id { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (typeof(ISoftDelete).IsAssignableFrom(entityType.ClrType))
{
entityType.AddSoftDeleteQueryFilter();
}
}
}
public static void AddSoftDeleteQueryFilter(
this IMutableEntityType entityData)
{
var methodToCall = typeof(SoftDeleteQueryExtension)
.GetMethod(nameof(GetSoftDeleteFilter),
BindingFlags.NonPublic | BindingFlags.Static)
.MakeGenericMethod(entityData.ClrType);
var filter = methodToCall.Invoke(null, new object[] { });
entityData.SetQueryFilter((LambdaExpression)filter);
}
private static LambdaExpression GetSoftDeleteFilter<TEntity>()
where TEntity : class, ISoftDelete
{
Expression<Func<TEntity, bool>> filter = x => !x.SoftDeleted;
return filter;
}
public interface IBaseRepository<TDbModel> where TDbModel : BaseModel
{
public List<TDbModel> GetAll();
public TDbModel Get(Guid id);
public TDbModel Create(TDbModel model);
public TDbModel Update(TDbModel model);
public void Delete(Guid id);
}services.AddTransient<IBaseRepository<Car>, BaseRepository<Car>>();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace WebApi1.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace WebApi1.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static Random Rng = new Random();
private WeatherForecast[] forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Rng.Next(-20, 55),
Summary = Summaries[Rng.Next(Summaries.Length)]
}).ToArray();
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
/// <summary>
/// Get list of forecasts
/// </summary>
/// <returns></returns>
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("Get list of forecasts");
return forecasts;
}
/// <summary>
/// Get one of forecasts or 404 error
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
[HttpGet]
public ActionResult<WeatherForecast> Get(int num)
{
_logger.LogInformation($"Get forecasts[{num}]");
if (num >= 0 && num < forecasts.Length)
return forecasts[num];
else
return NotFound();
}
}
}
Как создать простое Rest API на .NET Core