How to return on client error message with status code

前端 未结 3 1082
名媛妹妹
名媛妹妹 2021-01-19 04:35

I tried to use this:

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

also I tried this one:



        
相关标签:
3条回答
  • 2021-01-19 05:09

    I was able to put a custom message in the error response body with the following code:

    Response.TrySkipIisCustomErrors = true;
    Response.Clear();
    Response.Write( $"Custom Error Message." );
    return new HttpStatusCodeResult( HttpStatusCode.InternalServerError );
    
    0 讨论(0)
  • 2021-01-19 05:27

    I have an ErrorController that help me throwing the errors and showing a nice error page, the use Response.StatusCode to return a different 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");
            }
    
    
            ...
    
        }
    }
    

    Edit For returning message-only to ajax results I use something like this in an actionFilter

            Response.StatusCode = 200;
    
            //Needed for IIS7.0
            Response.TrySkipIisCustomErrors = true;
    
            return new ContentResult {
                Content = "ERROR: " + Your_message,
                ContentEncoding = System.Text.Encoding.UTF8
            };
    
    0 讨论(0)
  • 2021-01-19 05:33

    To return a specific response code with a message from ASP.NET MVC controller use:

    return new HttpStatusCodeResult(errorCode, "Message");
    

    Make sure the method in the controller is type ActionResult, not ViewResult.

    0 讨论(0)
提交回复
热议问题