0

I want to restrict access to api when token passed in header does not match value in my configuration. I have created a custom guid in my project to prevent access to non matching token values or empty header values.

Using this setup how do I properly return a 404 or some other status from an action in a controller whose return type is a list of a specific type (used for returning JSON)?

  [HttpGet]
  [Route("getList")]
  public List<_Type> func([FromUri] int? value)
  {
      if (Request.Headers == null || !Request.Headers.Contains("token") || Request.Headers.GetValues("token").First() != ConfigurationManager.AppSettings["token"])
          throw new HttpException(404, "Not found");   //works but triggers a object null reference exeption
      return new List<_Type>();
  }
1
  • set the Response.StatusCode = 404 and throw an exception Commented May 2, 2017 at 20:03

2 Answers 2

2

You can change return type into IHttpActionResult. Ok() method takes an object as parameter so you can pass your collection.

[HttpGet]
  [Route("getList")]
  public IHttpActionResult func([FromUri] int? value)
  {
      if (Request.Headers == null || !Request.Headers.Contains("token") || Request.Headers.GetValues("token").First() != ConfigurationManager.AppSettings["token"])
          return NotFound();  //works but triggers a object null reference exeption
      return Ok(new List<_Type>());
  }
Sign up to request clarification or add additional context in comments.

Comments

1
[HttpGet]
[Route("getList")]
public ActionResult func([FromUri] int? value) {
    if (Request.Headers == null || !Request.Headers.Contains("token") || Request.Headers.GetValues("token").First() != ConfigurationManager.AppSettings["token"])
        return NotFound();
    return Json(new List<_Type>());
}

1 Comment

and, for your Scenario, consider usage of ActionFilter

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.