0

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);
    }
2
  • 1
    What values do you receive at: HttpResponseMessage responsePost = await client.PostAsJsonAsync("api/Employee", employee); ? Commented Jan 16, 2020 at 8:45
  • 1
    Oh. Found it. Console.WriteLine("Internal server Error: " + responsePost.ReasonPhrase); Commented Jan 16, 2020 at 9:14

1 Answer 1

1

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);
        }
Sign up to request clarification or add additional context in comments.

2 Comments

If it is update function, how it differentiate different update function? For example there is change password function and update employee function. Both also will update from employee table? Put another parameter in the put method?
Well that would depend on your logic. For example, if you have separate API for each function then you can catch the exception as shown above otherwise if you have only one API for change password and update employee (not preferred method), then you would have to handle the exception appropriately and send it back to your client. Basically the above method will only handle the exception for the current API call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.