给定此代码,C# REST API 的入口,
protected HttpResponseMessage ProcessRequest()
{
HttpResponseMessage _response = null;
try
{
//request is processed.
object _obj = ExecuteEvent();
//response object is created with success status and response content is assigned in the required mediatype format.
_response = Request.CreateResponse(HttpStatusCode.OK, Constants.ServiceConstants.VALUE);
_response.Content = new StringContent(System.Web.Helpers.Json.Encode(_obj), Encoding.UTF8, Constants.ServiceConstants.MEDIATYPE);
}
catch
{
}
return _response;
}
为每个请求返回 200 响应并将内容设置为如上所述的序列化 JSON,这是处理此问题的正确方法还是错误方法?
我本以为我们绝对不应该为每个请求返回 200 OK。
此代码将在 ExecuteEvent
中抛出异常,假设用户未经授权,但是,我们实际上不应该告诉调用者他们的请求未经授权吗?
最佳答案
您应该根据方法中发生的事情发回 HTTP 状态。如果一切正常,您将发回 OK。如果失败,您应该发回相应的状态码。
例如,如果 ExecuteEvent 抛出一条消息表明用户未被授权,您将发回 HTTP 停留代码 Forbidden (a 403)。
可以看到微软所有的状态码here您可以获得数字列表及其含义 here .大多数情况下,这两个列表相互对应,只是组织方式稍有不同。
希望对您有所帮助。
关于c# - REST API 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36529376/