0

I know how to return HTTP status codes to indicate if an AJAX call failed or succeeded using the HttpStatusCode and HttpStatusCodeResult classes, and I know how to return objects using Json(), but now I need to return both a HttpStatusCode.BadRequest and a string containing the error message. I need to return the HttpStatusCode so the AJAX call goes to the error property, and can access the error message.

How would I do this in C#?

UPDATE I found this bit of code:

 return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "This is an error message");

That works alright and I can see the response in my browser. How would I extract the message part of this to display it in an alert through jQuery?

10
  • ASP.NET MVC HttpStatusCodeResult Class Commented Mar 30, 2015 at 21:40
  • In your $.ajax() error handler, the error message should appear as the second argument, textStatus. Commented Mar 30, 2015 at 21:43
  • Got it all working now, it was response.statusText Commented Mar 30, 2015 at 21:45
  • Yup, that should also work. Commented Mar 30, 2015 at 21:46
  • 1
    Try the third argument. Commented Mar 31, 2015 at 21:52

2 Answers 2

1

Are you trying to do something like this,

try
{
} 
catch (Exception ex)
{
   return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}

Edit:

error: function (xhr, textStatus, errorThrown) {                
              //errorThrown will have the message you sent. 
              //Also, debug and see the values in xhr object.
            }
Sign up to request clarification or add additional context in comments.

Comments

0

simply you can use this line in your method,

 [HttpGet]
 [Route("Your web api path",Name = "Your web api path")]
 public HttpResponseMessage test ()
 {
     //some codes here 

 return Request.CreateResponse(HttpStatusCode.Ok,[You want to return value]);
 }

I hope this can be help you, cheers dude,

Edit : Also you should add them in your codes, System.Web.Http; System.Net.Http and "System.Web.Http.Results;"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.