【问题标题】:Returning Error Code from Controller with System.Web.Http使用 System.Web.Http 从控制器返回错误代码
【发布时间】:2018-12-11 21:44:46
【问题描述】:

我编写了一个非常轻量级的 REST API,用于验证用户。我想将验证作为 JSON 对象返回,我可以这样做,但是如果缺少参数,我想用一些信息来回退错误。这是我的控制器

    public class GraphAccessController : ApiController
    {
        private UserValidation _userValidation;
        private UserPermissions _userPermissions;
        string _application;

        public GraphAccessController()
        {
            _userValidation = new UserValidation();
            _userPermissions = new UserPermissions();
        }
        public object GetUserValidation(string application)
        {

            if (string.IsNullOrEmpty(application))
            {
                return StatusCode(HttpStatusCode.MethodNotAllowed);
                //return new HttpResponseException(HttpStatusCode.MethodNotAllowed);
            }
            try
            {
                _application = application;
                ValidateUser(WindowsIdentity.GetCurrent(), application);
                return _userValidation;
            }
            catch (HttpResponseException e)
            {
                string error = e.ToString();
                return StatusCode(HttpStatusCode.InternalServerError);

            }
        }....(other private calls for validation)
{

当“应用程序”被传入时,我得到了一个不错的 JSON 对象。但是,当我在检查 IsNullOrEmpty 时尝试向用户返回错误时,如果我只是使用 PostMan 调用:

return StatusCode(HttpStatusCode.MethodNotAllowed)

状态设置为“405 Method Not Allowed”,但我想传递一些文本来说明它失败的原因。所以我尝试了:

throw new HttpResponseException(HttpStatusCode.MethodNotAllowed);

这只是在我的控制下停止执行。所以我做了一个 return 而不是 throw 我得到了 200 的状态(表明一切都很好)但是 JSON 标头数据:

{ “回复”: { “版本”: { “_专业”:1, “_Minor”:1, “_Build”:-1, “_修订”:-1 }, “内容”:空, “状态码”:405, "ReasonPhrase": "方法不允许", “标题”:[], “请求消息”:空, “IsSuccessStatusCode”:假 }, "Message": "处理 HTTP 请求导致异常。请查看 'Response' 返回的 HTTP 响应 此异常的属性以获取详细信息。", “数据”: {}, “内部异常”:空, “目标站点”:空, “堆栈跟踪”:空, “帮助链接”:空, “来源”:空, “HResult”:-2146233088 }

从 catch 中的代码可以看出,我也在尝试做同样的事情。如何将带有相应信息文本的 StatusCode 返回给调用者,以便他们检查状态,如果不是 200,则检查正文中的错误文本?

谢谢

【问题讨论】:

  • 你检查过这个:docs.microsoft.com/en-us/aspnet/web-api/overview/… 吗?我认为使用HttpResponseMessage 是处理您想要的正确方法。
  • 我查看了这个并尝试了这个代码:string error = "Application cannot be empty"; HttpResponseMessage 响应 = Request.CreateResponse(HttpStatusCode.NotImplemented, Encoding.Unicode); response.Content = new StringContent(error);返回响应;但是当我这样做时,我收到此错误:“ExceptionMessage”:“找不到方法:'System.Net.Http.HttpRequestMessage System.Web.Http.ApiController.get_Request()'。”,

标签: c# rest controller system.web.http


【解决方案1】:

尝试使用所需的 HttpStatusCode 返回内容响应,如下所示:

catch (HttpResponseException e)
        {
            string error = e.ToString();
            return Content(HttpStatusCode.MethodNotAllowed, error);
        }

【讨论】:

  • 谢谢!这做到了。我没有返回内容。
猜你喜欢
  • 2020-08-13
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
  • 2021-09-11
  • 1970-01-01
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多