Пытаюсь реализовать клиент серверное академическое приложение. Пытаюсь мигрировать на современный фреймворк и наступил на грабли...
Серверная часть: Модель:
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Department { get; set; }
public string ImagePath { get; set; }
public DateTimeOffset DateAndTime { get; set; }
Контекст:
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employee { get; set; }
public EmployeeContext(DbContextOptions<EmployeeContext> options)
: base(options)
{ }
public EmployeeContext()
{
}
}
Репозиторий:
public interface IEmployeeRepository
{
Employee Add(Employee employee);
Employee Get(int id);
IQueryable<Employee> GetAll();
void Remove(int id);
bool Update(Employee employee);
}
Реализация(по поводу id не ругайтесь, пока для теста сделал):
public class EmployeeRepository
{
//private List<Employee> _employee = new List<Employee>();
EmployeeContext db = new EmployeeContext();
private int _nextId = 1;
public IQueryable<Employee> GetAll()
{
EmployeeContext empContext = new EmployeeContext();
try
{
return empContext.Employee.AsQueryable();
}
catch (Exception err)
{
throw new Exception(err.Message);
}
}
public Employee Add(Employee employee)
{
using (EmployeeContext empContext = new EmployeeContext())
{
try
{
employee.Id = _nextId++;
empContext.Employee.Add(employee);
empContext.SaveChanges();
}
catch (Exception err)
{
throw new Exception(err.Message);
}
return employee;
}
}
public Employee Get(int id)
{
using (EmployeeContext empContext = new EmployeeContext())
{
return empContext.Employee.SingleOrDefault(c => c.Id == id);
}
}
public void Remove(int id)
{
using (EmployeeContext empContext = new EmployeeContext())
{
try
{
Employee employeeToRemove = new Employee
{
Id = id
};
empContext.Employee.Attach(employeeToRemove);
empContext.Employee.Remove(employeeToRemove);
empContext.SaveChanges();
}
catch (Exception err)
{
throw new Exception(string.Format("Сотрудника не существует или запись удалена!" + err.Message));
}
//OnChanged.Invoke(null, new EventArgs());
}
}
public bool Update(Employee employee)
{
using (EmployeeContext empContext = new EmployeeContext())
{
var index = empContext.Employee.FirstOrDefault(c => c.Id == employee.Id);
if (index != null)
{
return false;
}
empContext.Employee.Remove(index);
empContext.Employee.Add(employee);
return true;
}
}
}
Пространства имен в контроллере:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApiCoreTest.Model;
using System.Net.Http;
using System.Net;
using System.Net.Http.Formatting;
Контроллер:
[Route("api/[controller]")]
public class EmployeeController : Controller
{
static readonly IEmployeeRepository repository = new
EmployeeRepository();
public EmployeeController() { }
public IEnumerable<Employee> GetAllEmployee()
{
return repository.GetAll();
}
public Employee GetEmployee(int id)
{
Employee item = repository.Get(id);
if (item == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
return item;
}
public IEnumerable<Employee> GetEmployeeByName(string name)
{
return repository.GetAll().Where(
p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase));
}
public HttpResponseMessage PostEmployee(Employee item)
{
item = repository.Add(item);
var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
return response;
}
//public void PutEmployee(int id, Employee employee)
//{
// employee.Id = id;
// if (!repository.Update(employee))
// {
// throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
// }
//}
public HttpResponseMessage DeleteEmployee(int id)
{
repository.Remove(id);
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
}
В контроллере ругается на HttpResponseException и CreateResponse
Как можно это побороть? Клиент написан на WFP, этот метод прибайндин к DataGrid для получения списка Employee:
private void BindEmployeeList()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:55872");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/[controller]").Result;
if (response.IsSuccessStatusCode)
{
var employees = response.Content.ReadAsAsync<IEnumerable<Employee>>().GetAwaiter().GetResult();
grdEmployee.ItemsSource = employees;
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}