0

I am trying to return 500 Http status code and set a message in Response.Write() but the browser displays message, "The page cannot be displayed because an internal server error has occurred" and ignores Response.Write() after setting status code to 500.

[WebMethod]

public void ServiceCheckTest()
{
    try
    {
         HttpContext.Current.Response.Write("Request has been processed");//This works fine
    }
    catch
    {
         HttpContext.Current.Response.StatusCode = 500;
         //Setting StatusCode = 500 ignores the following message
         HttpContext.Current.Response.Write("Request could not be processed. Please try again later");
    }
}

Is there a way i can set the http status code to 500 and also set a custom message in Response.Write.

JMP
  • 4,417
  • 17
  • 30
  • 41
Vab
  • 1
  • The browser will always display that kind of message ignoring the response's body whenever it finds a 5XX response code, have you checked the response with other program like postman? – Gusman Oct 26 '20 at 12:40
  • See : https://learn.microsoft.com/en-us/dotnet/api/system.web.httpresponse.write?view=netframework-4.8 – jdweng Oct 26 '20 at 12:41
  • Did you try to set the first message? – Serkan Yıldırım Oct 26 '20 at 13:03
  • `asmx` refers to an ancient SOAP stack. SOAP has *strict specifications* on how messages are defined and what is contained in error responses. You **can't** just return any kind of content, or write directly to the response. Clients **expect** errors to be well formed – Panagiotis Kanavos Oct 26 '20 at 16:02
  • You shouldn't be using ASMX at all though. It was replaced by WCF in 2008 and doesn't support any of the interoperability standards defined between 2003 and 2008 or even later. Both stacks handle errors already though – Panagiotis Kanavos Oct 26 '20 at 16:04
  • BTW what you wrote isn't a WebMethod or ASMX method. Nobody will be able to call it thing because it breaks SOAP and returns completely unstructured data. SOAP **is XML**, not raw text – Panagiotis Kanavos Oct 26 '20 at 16:05
  • If you check the two duplicates you'll see that while ASMX had very basic support for faults, WCF allows you to specify your own fault classes – Panagiotis Kanavos Oct 26 '20 at 16:09

0 Answers0