Steve
Steve

Reputation: 4523

application/business logic behind web api and validation error in UI?

I understand that "service" layer where I have my business/application logic should be behind "web api" layer. Here I have my "web api" layer which have CRUD methods.

So, if I want to add the application/business logic, for example, before add new employee, I want to check to make sure employee name must be unique, I shall do so as below in my web api PostEmployee method?

namespace WebApi.Controllers
{
public class EmployeeController : ApiController
{
    private AppDbContext db = new AppDbContext();

    // POST api/Employee
    [ResponseType(typeof(Employee))]
    public IHttpActionResult PostEmployee(Employee employee)
    {

        // application / business logic to put here, right?

        db.Employees.Add(employee);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);
    }

}
}

In my UI, I use Console project which has this add employee method and application / business logic validation error to show here as shown?

static async Task AddEmployee()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(webAPIURL);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var employee = new Employee();

            //POST Method
            Console.Write("Enter your name: ");
            employee.Name = Console.ReadLine();

            Console.Write("Enter your position: ");
            employee.Position = Console.ReadLine();

            Console.Write("Enter your age: ");
            employee.Age = Convert.ToInt16(Console.ReadLine());

            Console.Write("Enter your salary: ");
            employee.Salary = Convert.ToInt16(Console.ReadLine());

            HttpResponseMessage responsePost = await client.PostAsJsonAsync("api/Employee", employee);
            if (responsePost.IsSuccessStatusCode)
            {
                // Get the URI of the created resource.
                Uri returnUrl = responsePost.Headers.Location;
                if (returnUrl != null)
                {
                    Console.WriteLine("Employee data successfully added.");
                }
                //Console.WriteLine(returnUrl);
            }
            else
            {
                // application / business logic validation error to show here?

                Console.WriteLine("Internal server Error");
            }
        }

    }

Found partial solution (below). But how to print the exception in console ui?

// POST api/Employee
    [ResponseType(typeof(Employee))]
    public IHttpActionResult PostEmployee(Employee employee)
    {
        var duplicateName = db.Employees.Where(b=>b.Name == employee.Name).SingleOrDefault();
        if (duplicateName != null)
        {
            var msg = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("Duplicate employee name found. ")),
                ReasonPhrase = "Duplicate"
            };
            throw new HttpResponseException(msg);
        }

        db.Employees.Add(employee);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);
    }

Upvotes: 0

Views: 362

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 8311

If you have to get the error message from the HttpResponseMessage you have to get the HttpError object as shown below. The HttpError object then contains the ExceptionMessage, ExceptionType, and StackTrace information:

        if (responsePost.IsSuccessStatusCode)
        {
            // Get the URI of the created resource.
            Uri returnUrl = responsePost.Headers.Location;
            if (returnUrl != null)
            {
                Console.WriteLine("Employee data successfully added.");
            }
            //Console.WriteLine(returnUrl);
        }
        else
        {
            // application / business logic validation error to show here?
            HttpError error = responsePost.Content.ReadAsAsync<HttpError>().Result;
            Console.WriteLine("Internal server Error: "+error.ExceptionMessage);
        }

Upvotes: 1

Related Questions