如何在客户端返回错误消息,状态码(How to return on client error mes

2019-07-21 05:59发布

我试图用这样的:

return Request.CreateResponse(HttpStatusCode.InternalServerError, "My message");

同时我想这一个:

return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "My message");

但是,我看到我的浏览器500错误,虽然在显示像“我的信息”的任何消息。

Answer 1:

为了从ASP.NET MVC控制器使用的消息返回一个特定响应代码:

return new HttpStatusCodeResult(errorCode, "Message");

确保在控制器的方法是键入的ActionResult,没有的ViewResult。



Answer 2:

我有一个ErrorController,帮助我扔了错误,并呈现出不错的错误页面,使用Response.StatusCode返回不同的StatusCode

namespace Site.Controllers {

    [OutputCache(Location = OutputCacheLocation.None)]
    public class ErrorController : ApplicationController {

        public ActionResult Index() {
            ViewBag.Title = "Error";
            ViewBag.Description = "blah blah";
            return View("Error");
        }

        public ActionResult HttpError404(string ErrorDescription) {
            Response.StatusCode = 404;
            ViewBag.Title = "Page not found (404)";
            ViewBag.Description = "blah blah";
            return View("Error");
        }


        ...

    }
}

编辑返回的消息只给阿贾克斯的结果我用这样的事情在一个ActionFilter

        Response.StatusCode = 200;

        //Needed for IIS7.0
        Response.TrySkipIisCustomErrors = true;

        return new ContentResult {
            Content = "ERROR: " + Your_message,
            ContentEncoding = System.Text.Encoding.UTF8
        };


文章来源: How to return on client error message with status code