Thodor12
Thodor12

Reputation: 149

ASP.NET MVC Web Api only available in 1 Http Method but not throwing Http Statuscode 406 if it has another method

So, my main question is in the title. How is it possible to avoid the browser to throw Http Statuscode 406 once an invalid method is supplied?

I've tried by default to allow all incoming methods by using [AcceptVerbs("GET", "POST", "PUT", "DELETE")] and after that to filter out the actual allowed method by using this method:

private bool CheckAllowedMethod(HttpMethod allowed, HttpMethod given)
{
    if (allowed == given)
    {
        return true;
    }

    throw new InvalidMethodException("This method is not available over " + Request.Method.Method);
}

Even though this works it isn't very neat. The behaviour I want to avoid when using [HttpPost], or any equivalent of those, is that the browser throws a Http Statuscode 406 and literaly prints nothing to the site even though I want to display a JSON string at all times.

So, is this possible any easier or do I have to use my current method?

Full code:

[AcceptVerbs("GET", "POST", "PUT", "DELETE")]
[Route("api/Auth/Login/{apikey}")]
public HttpResponseMessage GenerateLoginCode(string apikey = "") {
 HttpResponseMessage response = CreateResponse();

 try {
  CheckAllowedMethod(HttpMethod.Post, Request.Method);

  ChangeContent(response, JSONString.Create(Apikey.Login(apikey)));
 } catch (Exception ex) {
  ChangeContent(response, Error.Create(ex));
 }

 return response;
}

private HttpResponseMessage CreateResponse() {
 return Request.CreateResponse(HttpStatusCode.OK);
}

private void ChangeContent(HttpResponseMessage res, string data) {
 res.Content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");
}

private bool CheckAllowedMethod(HttpMethod allowed, HttpMethod given) {
 if (allowed == given) {
  return true;
 }

 throw new InvalidMethodException("This method is not available over " + Request.Method.Method);
}

Upvotes: 0

Views: 257

Answers (1)

Tomas Aschan
Tomas Aschan

Reputation: 60664

I would not do this via accepting all methods and filtering manually, but rather with a middleware that catches the error response and rewrites it.

I dug quite deeply into error handling in Web API 2 earlier this year, and expanded on my findings in this blog post. If you do something similar to that, you could handle the exception from a disallowed method in a special catch clause in the middleware and write whatever you want to the response.

Upvotes: 2

Related Questions