Home Handling NotFound response from Web API
Reply: 1

Handling NotFound response from Web API

Drac
1#
Drac Published in 2018-02-13 21:27:42Z

One of my ASP.NET Web API project has such code:

public HttpResponseMessage GetStatusById(int sid)
{
    try
    {
        var mds = TheRepository.GetStatusById(sid);
        if (mds != null)
        {
            return Request.CreateResponse(HttpStatusCode.OK, TheModelFactory.Create(mds));
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
    }
}

In the same solution, but in another project I'm coding client (ASP.Net Website), which will read and write data through this WebAPI.

At first client should check if record already exists in database:

public async Task<ActionResult> Create([Bind(Include = "id,description")] MDS mds)
{
    if (mds == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "No data given to server");
    }
    else
    {
        MDS reqMds = await _mdApiService.GetMDS ByStatus(Convert.ToInt32(mds.Id));                    

        if (reqMds == null )
        {
            await _mdApiService.CreateMDS(mds);
        }
        else
        {
            return new HttpStatusCodeResult(HttpStatusCode.Conflict, "Already exists");
        }
    }
    return View("Details", mds);
}

When I call this method, I get NotFound-Page in my browser instead of getting Response to Client (website) and parsing it. The goal is to show error from WebSite Project, not from Web API project.

What is the right way to check on client that record already exists through Web API?

Drac
2#
Drac Reply to 2018-02-16 19:51:51Z

I decided to edit my server Web API to check for duplicate entry. On the client only transmitting actions from user to API.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.393944 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO