How to optimize Web API Code?

Wappla 1 Reputation point
2022-02-03T12:31:02.327+00:00

How could you optimize that code for faster response?

public ActionResult Details(int id)
        {
            DTOLibrary.PoliticianDTO politician = null;

            using(var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:61442/api/");

                var responseTask = client.GetAsync("politicians/" + id);
                responseTask.Wait();

                var result = responseTask.Result;
                if(result.IsSuccessStatusCode)
                {
                    // Install-Package Microsoft.AspNet.WebApi.Client -ProjectName Client
                    var readTask = result.Content.ReadAsAsync<DTOLibrary.PoliticianDTO>();
                    readTask.Wait();

                    politician = readTask.Result;
                }
            }

            return View(politician);
        }


[ResponseType(typeof(Politician))]
        public IHttpActionResult PostPolitician(DTOLibrary.PoliticianDTO politician)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            Politician p = new Politician();
            p.fromDto();
            db.politicians.Add(p);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = politician.Id }, politician);
        }

// PUT: api/Politicians/5
[ResponseType(typeof(void))]
public IHttpActionResult PutPolitician(int id, DTOLibrary.PoliticianDTO)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

        if (id != politician.Id)
        {
            return BadRequest();
        }

        Politician p = db.stores.Find(politician.id);
        db.Entry(p).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!PoliticianExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

// POST: Store/Create
[HttpPost]
public ActionResult Create([Bind(Include = "id, name, party")] DTOLibrary.PoliticianDTO politician)
{
using(var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:60183/api/");

            var postTask = client.PostAsJsonAsync<DTOLibrary.PoliticianDTO>("politicians", politician);
            postTask.Wait();

            var result = postTask.Result;
            if(result.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
        }

        return View();

    }
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
317 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,181 Reputation points
    2022-02-04T00:03:10.35+00:00

    you also should not be converting async calls to sync with .Wait() and .Result. This will degrade scaling.

    also you concurrency detection is poor. for example:

    user 1 call up Politician A
    user 1 starts making changes
    user 2 call up Politician A
    user 2 starts making changes
    user 2 save changes
    user 1 save changes

    user 1 overwrites user 2 changes because there is no concurrency check. (your code only handles a race condition if the two db saves are running concurrently.)

    I'd give you a C- on the code. Functional, but not correct or performant.

    0 comments No comments