所以,我的主要问题在标题中。一旦提供了无效的方法,如何避免浏览器抛出Http Statuscode 406?
默认情况下,我尝试使用[AcceptVerbs("GET", "POST", "PUT", "DELETE")]允许所有传入的方法,然后使用此方法过滤出实际允许的方法:
private bool CheckAllowedMethod(HttpMethod allowed, HttpMethod given)
{
    if (allowed == given)
    {
        return true;
    }
    throw new InvalidMethodException("This method is not available over " + Request.Method.Method);
}即使这样可以工作,它也不是很整洁。在使用[HttpPost]时,我想要避免的行为是,浏览器抛出一个Http Statuscode406,即使我想一直显示一个JSON字符串,也不会打印任何内容到站点。
那么,这是否可能变得更简单,或者我必须使用我当前的方法?
完整代码:
[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);
}发布于 2016-07-17 00:24:09
我不会通过接受所有方法和手动过滤来做到这一点,而是使用一个捕获错误响应并重写它的中间件。
我深入研究了WebAPI2 earlier this year中的错误处理,并在this blog post中扩展了我的发现。如果您执行类似的操作,则可以在中间件中的一个特殊catch子句中处理来自disallowed方法的异常,并向响应中写入任何您想要的内容。
https://stackoverflow.com/questions/38413061
复制相似问题