MVC 3 + REST return custom http error? - asp.net-mvc-3

In my application I am trying to get it so that when a REST api call is made, if there is an error that it return a proper status code then either Json or Xml in the body of the response.
So 400: { 'ErrorCode': '400', 'Reason' : 'You did something wrong..' }
or 400: <Error><ErrorCode>400</ErrorCode><Reason>You did something wrong</Reason></Error>
However I can't seem to find how to set the status and body to make this happen. Using fiddler inspect whats being passed back and fourth I've found that if I return a normal ActionResult then I can return the body message ok but the status is 200. If I use HttpException then I can set the status code but the body message is returned as a large html document. I've tried using HttpStatusCodeResult but that just seems to fail and return a 302.
I'm a bit stumped.

Try Response.StatusCode = (int)HttpStatusCode.BadRequest; in your action method. Check out this article at develoq for a short tutorial: http://develoq.net/2011/returning-a-body-content-with-400-http-status-code/

Web API can handle this in various ways, but if you want to stick to ASP.NET MVC then use the code below:
Response.StatusCode = 500;
Response.TrySkipIisCustomErrors = true;
return Content("Error description goes here.", "text/plain");

Check out MVC 4 Beta, there is a new feature called Web API that will help you solve this issue.

Related

WebApi response codes

So let's say I have a WebApi controller called UsersController. Let's look at the following examples:
1.Navigating to /Users/1 returns JSON of a user with Id = 1. HTTP response code will be 200.
2.Navigating to /User/1 (note I misspelled the URL!) will return response code 404. I do not even need to do anything, my web server will return code 404 for me.
Now the question: what response code (200 or 404) should be returned by the URL /Users/2, if user with Id = 2 does not exist in the database? And why.
You should return NotFound (404), because the url is valid but the required resource doesn't exists. check this.

Different response from a controller method based on HTTP Response code

How do you write a controller method which can either return a View or HTTP response status code based on if its 200 then view else the response status code.
#RequestMapping(value="/",method=RequestMethod.GET)
public String showLanding()
{
return View.Landing;
}
I want to handle in case of 401, 403, 500 etc. just status code should be returned instead of view.
To return the 403- Unauthorized status code,
#RequestMapping(value="/",method=RequestMethod.GET)
public String showLanding()
{
return HttpStatus.UNAUTHORIZED;
}
See this:
http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/http/HttpStatus.html?is-external=true
How to respond with HTTP 400 error in a Spring MVC #ResponseBody method returning String?
You could also check out the #ResponseStatus annotation as well as ResponseEntity (for more dynamic scenarios)
I'm far from suggesting that you should do flow control with Exceptions - but those HTTP statuses are errors and exceptions. So you might want to throw business exceptions from your controller methods and then handle those using #ExceptionHandlers.
You can also target a subset of Controllers and assist those with Exception handling using #ControllerAdvice.

How to handle application errors for json api calls using CakePHP?

I am using CakePHP 2.4.
I want my frontend make api calls to my CakePHP backend using ajax.
Suppose this is to change passwords.
Change password action can throw the following application errors:
old password wrong
new password and confirm new passwords do not match
In my frontend, I have a success callback handler and a error callback handler.
The error callback handler handles all the non 200 request calls such as when I throw NotFoundException or UnAuthorizedAccessException in my action.
The success callback handler handles all the 200 request calls including of course, the above 2 scenarios.
My questions are:
Should I continue to do it this way? Meaning to say, inside all success callback handler, I need to watch out for application success and application error scenarios.
Should I send application errors back with actual HTTP error codes?
if I should do 2, how do I implement this in CakePHP?
Thank you.
Don't use http error codes for system errors like:
old password wrong
new password and confirm new passwords do not match
etc etc...
Now using success handler you can show messages and code flow as:
Create Ajax post or get to submit the form, I am showing you post example
var passwordValue = $('#password').val();
$.post( "/updatePassword", { passwordText: passwordValue })
.done(function(response) {
if(response.status === 'Success'){
// Success msg
// whatever
}else{
// Error msg
// whatever
}
});
json response would like:
{
"status": "Failed/Success",
"message": "old password wrong."
}
Create one function in controller
public function updatePassword() {
$myModel = $this->MyModel->find('first' // YOUR CODE LOGIC);
if($this->request->is('ajax') {
$this->layout=null;
// What else?
echo json_encode($myModel);
exit;
// What else?
}
}
Do something like this, hope it will solve your query!

Returning HTTP 403 substatus from Asp.Net WebApi controller

I'd like to return Http 403 errors from my Asp.Net WebApi controllers when the user does not have permission to perform certain tasks.
However, I'd like to use a substatus on this to give further details about the error, along with the error message.
At the moment, what I get is
HTTP/1.1 403 Read access forbidden
but what I'd like to see is
HTTP/1.1 403.2 Read access forbidden
The code I'm using currently:
[HttpGet]
public EnrollmentDetail Details(int id)
{
var enrollmentDetail = _context.GetEnrollmentDetail(id);
if (!enrollmentDetail.R)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)
{
ReasonPhrase = "Read access forbidden"
});
}
return enrollmentDetail;
}
I can't find any information any where on how to add these sub-statuses to the response. Is there any way it can be done with the built-in classes? If not, is there a way to write a custom HttpException which could do this for me?
That's because sub-statuses are not part of the HTTP spec and should not be used. If you want to send more details about the problem you encountered, take a look at Json-problem

How to use Fiddler 2 to compose a request?

I am using asp.net web api and I want to try to see if my method work. The way I see people do this alot is through fiddler. I am trying to do this myself but I can't get it to work.
I go to the composer tab and do this.
public IQueryable<FoodLogRecord> Get(string email)
{
return null;
}
but I get a 404 back. I also put a break point in the method and it never goes in.
Use the URL
http://localhost:50570/api/foodlog?email=c
Remove the Content-Length and the text from the request body. You can't send a body with a GET request.
You should be able to use the following URL with the code changes below: http://localhost:50570/api/foodlog/c
public IQueryable<FoodLogRecord> Get([FromUri] string email)
{
return null;
}

Resources