C#C
C#3y ago
53 replies
Ysehporp

✅ Sending an HTTP Exception in Web API

I am having some trouble with sending an HTTP exception in web api as it seems how its dont has changed over the course of different .net versions.
There seems to be an issue of what return type I have, but I found examples online where people were able to do it with an ActionResult.
I found examples which implemented it like this but it will not compile for me because it cannot convert the return type.

 [HttpPost]
    [Route("login")]
    public ActionResult<String> login(Login req)
    {
     
      LoginReturn r = new LoginReturn();
            Account query = (from m in msgDB.accounts
                            where m.userID == req.username
                            select m).FirstOrDefault<Account>();
            if (query!= null)
            {

            }
            else
            {
                //Why doesn't this compile?
                return new HttpStatusCodeResult(HttpStatusCode.NotFound, "No user exists with that ID");
            }
      r.userID = req.username;
      r.token = "Fake Token";

      return JsonConvert.SerializeObject(r);

    }


I have also tried what is shown on the learn microsoft page where it says essentially to do
  throw new HttpResponseException(HttpStatusCode.NotFound);

However doing so causes my server to encounter an unhandled exception and cease to work.

What is the correct way of doing this in .net 6???
Was this page helpful?