Server validation - response message? - c#

I am coding server validation with C# and HttpResponseMessage. I need to send response back to the client with certain message, that the data sent is not valid. Which response code should I choose from this list?
https://msdn.microsoft.com/en-us/library/system.net.httpstatuscode(v=vs.110).aspx
Could I also customize the message so that I know which field got invalid data?
Note: MVC 4, Visual Studio 2010.
Here is my post function:
// POST api/Default1
[HttpPost]
public HttpResponseMessage PostUserProfile(HttpRequestMessage req)
{
UserProfile up = new UserProfile();
string jsonContent = req.Content.ReadAsStringAsync().Result;
if (ModelState.IsValid)
{
up = JsonConvert.DeserializeObject<UserProfile>(jsonContent);
if (up.userName.Length <= 50 &&
up.email.Length <= 60)
{
db.UserProfiles.Add(up);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, up);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = up.UserId }));
return response;
}
else
{
// finish the server validation
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.InternalServerError, up);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = up.UserId }));
return response;
}
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}

Some people suggested BadRequest which is Http message 400:
Equivalent to HTTP status 400. BadRequest indicates that the request could not be understood by the server. BadRequest is sent when no other error is applicable, or if the exact error is unknown or does not have its own error code.
I don't think its suitable in this case since the browser does not see it as error, as if I sent OK message back to the client.
I think NotFound is more appropriate:
Equivalent to HTTP status 404. NotFound indicates that the requested resource does not exist on the server.
The browser sees it as error and therefore sent to the error handler in the jQuery AJAX object. So you can properly handle it, i.e update some message box in the html to let the user know that the server/database simply does not contain that resource or row in the table.

Related

Unauthorized returns text/html instead of application/json

I have a controller action in my WebAPI server that returns a 401 Unauthorized. The action also returns other error status codes such as 401, 409 and 500 as well as 200. All status codes add a DTO serialized to JSON all are working as expected.
For 401 I'm doing:
return Unauthorized(new UnauthorizedError() {
Id = 1, //int
Error = Error.UserNotFound, //enum
Message = "User not found" //string
});
The clients handles the 401 and reads the content as Unauthorized:
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
var result = await response.Content.ReadAsAsync<UnauthorizedError>(ct);
}
But just for these status code, I'm getting an exception:
No MediaTypeFormatter is available to read an object of type 'UnauthorizedError' from content with media type 'text/html'.
The app is running in IIS. Might it be the case that IIS is overriding the response type for 401? Is there a way to force a json response type on this action?

Get body of request in ASP.NET Web Api

I faced problem like this.
I have method in controller, that receive data in body of POST request.
Here is method.
// POST: api/StartWorkingDays
[ResponseType(typeof(StartWorkingDay))]
public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.StartWorkingDays.Add(startWorkingDay);
db.SaveChanges();
return Json(new { Result = "Success", Message = "Saved Successfully"});
//return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
}
How I can see body of request that I receive?
Thank's for help.
[HttpPost]
public HttpResponseMessage PostStartWorkingDay([FromBody] StartWorkingDay startWorkingDay)
{
//here above startWorkingDay is body your mobile developer will send
//you and data can be viewed while debugging ,
//tell mobile developer to set content-type header should be JSON.
return Request.CreateResponse(HttpStatusCode.Created, "Success");
}
Why your return type is Json ? you should use HttpResponse . I believe you are using Web api 2 . With Attribute routing and if you want to send response in json format then remove Xml formatter from WebApiConfig.cs file inside App_Start folder

ApiController BadRequest(string message) method is not returning the custom message passed in parameter

On my console application I am making following webClient Request to upload the data.
using (var client = new WebClient())
{
client.Headers.Clear();
client.Headers.Add("Content-Type", "application/json; charset=utf-8");
client.UploadStringCompleted += (data, exception) =>
{
if (exception.Error != null)
{
_log.Error("Error While Posting XYZSets data {0}", exception.Error);
}
client.Dispose();
};
var ApplicationUrl = string.Format("{0}/api/AAA/PostXYZSets", ConfigurationManager.AppSettings["ApplicationUrl"]);
client.UploadStringAsync(new Uri(ApplicationUrl), jsonData);
}
In my MVC application at some point I am returning the IHttpActionResult by following code.
[ServiceAuthentication]
public IHttpActionResult PostXYZSets(XYZSet[] xYZSets)
{
return BadRequest("My Custom Error message");
}
But when UploadStringCompleted method receives exception, I nowhere find "My Custom Error message". it says (400) Bad Request.
Tell me what's wrong am i doing. thanks in advance.
The response is in the string returned, not in the header. It's there. Just read the return string as you would read an Ok response.

CURL Response "200", GetAsync "406"

I'm attempting to get a list of orders for my Xamarin Form application from my rails api.
Here is the code in my Xamarin Application that returns a "406":
async void UpdateOrders(string token)
{
// clear all the previous orders
orders.Clear();
var client = new HttpClient();
string url = "http://localhost:3000/api/orders?access_token=" + token;
Debug.WriteLine(url);
var response = await client.GetAsync(url);
//response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
Debug.WriteLine("this didn't work");
//var ex = CreateExceptionFromResponseErrors(response);
//throw ex;
}
else
{
// get the orders from the JSON
var orderItems = JsonConvert.DeserializeObject<List<Order>>(response.ToString());
// add all the orders to the page
orders = new ObservableCollection<Order>(orderItems);
}
}
url = "http://localhost:3000/api/orders?access_token=03642494d1631421a8b49a21085b53907e8498794c0dcacc61c7b4eefbf1b7eb"
** on a side-note the CreateExceptionFromResponseErrors line throws an error?
The same url above returns the following when I run it in CURL:
[{"id":1,"invoice":"HALP","description":"TESTING","weight":100.0,"length":48,"width":48,"height":48,"account_id":1,"driver_id":null,"status":"preview","account_quote":576,"driver_quote":432,"created_at":"2017-03-11T17:18:40.418Z","updated_at":"2017-03-11T17:18:40.418Z","driver_rating":5,"account_rating":5,"guid":"cfd12c84-b260-440c-a21a-7a8aab44b5ac"}]
Where am I going wrong?
HTTP 406 is the code for "not acceptable", meaning that your HttpClient is not properly configured to receive the payload from the server. You will need to configure your header for the correct content type.
See also:
What is “406-Not Acceptable Response” in HTTP?

asp.net webapi 2.0 handle wrong route

I have developed an API for an application and i have all routes set up, but when the users request the wrong action, the server returns 404 by default and i tried to find some way of changing that but i didnt find anything...
So lets say i have an api with the following route:
/api/school/1/classes
if the client requests
/api/school/1/classez
i want to return response code 501 or 405 instead of the default 404.
how can this be done?
Use Route attributes.
[HttpGet]
[Route("api/{id}/foo")]
public HttpResponseMessage foo(int id)
{
var response = new ApiResponse();
response.StatusCode = HttpStatusCode.OK;
return response;
}
[HttpGet]
[Route("api/{id}/{route}")]
public HttpResponseMessage bar(int id)
{
var response = new ApiResponse();
response.StatusCode = HttpStatusCode.BadRequest;
return response;
}
If they type it correctly then it will enter foo. Otherwise they will enter bar and you can handle that how ever you like.

Categories

Resources