简体   繁体   English

处理来自Web API的NotFound响应

[英]Handling NotFound response from Web API

One of my ASP.NET Web API project has such code: 我的ASP.NET Web API项目之一具有以下代码:

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. 在相同的解决方案中,但是在另一个项目中,我正在编码客户端(ASP.Net网站),该客户端将通过此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. 当我调用此方法时,我在浏览器中得到NotFound-Page,而不是获得对客户端(网站)的响应并进行解析。 The goal is to show error from WebSite Project, not from Web API project. 目的是显示来自WebSite Project的错误,而不是来自Web API项目的错误。

What is the right way to check on client that record already exists through Web API? 通过Web API检查客户端记录是否已经正确的正确方法是什么?

I decided to edit my server Web API to check for duplicate entry. 我决定编辑服务器Web API来检查重复项。 On the client only transmitting actions from user to API. 在客户端上,仅将操作从用户传输到API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM