首页 > 解决方案 > 使用 System.Web.Http 从控制器返回错误代码

问题描述

我编写了一个非常轻量级的 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 标头数据:

{“响应”:{“版本”:{“_Major”:1,“_Minor”:1,“_Build”:-1,“_Revision”:-1},“内容”:null,“StatusCode”:405, "ReasonPhrase": "Method Not Allowed", "Headers": [], "RequestMessage": null, "IsSuccessStatusCode": false }, "Message": "处理 HTTP 请求导致异常。请查看 HTTP 响应由此异常的 'Response' 属性返回以获取详细信息。", "Data": {}, "InnerException": null, "TargetSite": null,“StackTrace”:null,“HelpLink”:null,“Source”:null,“HResult”:-2146233088 }

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

谢谢

标签: c#restcontrollersystem.web.http

解决方案


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

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

推荐阅读