3

In one of my method I have to return IHttpActionResult from there in Web API 2. When succeeded it returns Ok() either it returns BadRequest() with some message. I am setting the message of BadRequest in the following way. But the problem is that I am unable to retrieve the error message from the called method. I am using Visual Studio 2013 Update 4 and the version is MVC 5.

return BadRequest("Error!  Error adding the device");

Please help. Thanks in advance.

3 Answers 3

6

After through research and study I found the solution. As this is a method of Web API, I have called it through my website. I have called it like the following way where RequestUrl is the url of this Web API method. If there are parameter(s) in the method, we have to write it in querystring.

HttpResponseMessage Response = null;
Response = client.GetAsync(RequestUrl).Result;
var stream = Response.Content.ReadAsStreamAsync().Result;

// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();

We also can have the response type using the following code.

Response.ReasonPhrase

And in this way I can have the message of BadRequest as well Ok. BINGO !!

Sign up to request clarification or add additional context in comments.

1 Comment

can you describe more specific how your solution work, do we still return BadRequest("Error! Error adding the device");
1

A custom error page could also cause your message not to appear. If your web.config file has something like the following, try removing it as it will intercept your 400 status errors: if you do have the following change existingResponse="Replace to existingResponse="PassThrough

<httpErrors existingResponse="Replace" errorMode="Custom">
  <remove statusCode="404" subStatusCode="-1"/>
  <error statusCode="404" prefixLanguageFilePath="" path="/myapppath/error404.aspx" responseMode="ExecuteURL"/>
</httpErrors

Comments

0

You have to set ReasonPhrase and wrap ResponseMessage to get an IHttpActionResult:

return this.ResponseMessage(new HttpResponseMessage
        {
          StatusCode = HttpStatusCode.BadRequest,
          ReasonPhrase = ex.Message
        });

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.