ASP.NET Core Web API - Return a string message with a NoContent Response? - asp.net-core

I have some records in the database that may or may not have some information for a certain column, and that's OK.
If a consumer of the endpoint runs into one of these records, I'd like to return "NoContent", because, well, there's No Content for that record that we can execute on. BUT ... I'd like to give them a message why, as there are two distinct reasons.
When looking at other status codes, this works:
return Accepted("I SEE THIS STRING!");
It actually shows up in the Response Header as the field location (I think, don't make me run this project again!)
This works for say Internal Server error:
return StatusCode(500, "I SEE THIS TOO!");
But, for NoContent there is no constructor like Accepted, where you can pass an object. Also, this shows me no string whatsoever:
return StatusCode(204, "WHY CAN'T I SEE THIS STRING?!");
Help!

204 (No Content) returns an HttpResponseMessage with, well, No Content.
If you do have content to return that the user can consume (the two reasons), then you don't have a No Content scenario.
Perhaps an Ok (200) with a custom ContentNotProvided class that holds a message, which can be consumed by the client, will do the trick?
Alternatively, return a BadRequest (400) with a message.

Related

Http status code when data not found in Database

I'm trying to understand which Http Status Code to use in the following use case
The user tries to do a GET on an endpoint with an input ID.
The requested data is not available in the database.
Should the service send back:
404 - Not Found
As the data is NOT FOUND in the database
400 - Bad Request
As the data in the input request is not valid or present in the db
200 - OK with null response
200 - OK with an error message
In this case we can use a standard error message, with a contract that spans across all the 200 OK responses (like below).
BaseResponse {
Errors [{
Message: "Data Not Found"
}],
Response: null
}
Which is the right (or standard) approach to follow?
Thanks in advance.
Which is the right (or standard) approach to follow?
If you are following the REST API Architecture, you should follow these guidelines:
400 The request could not be understood by the server due to incorrect syntax. The client SHOULD NOT repeat the request without modifications.
It means that you received a bad request data, like an ID in alphanumeric format when you want only numeric IDs. Typically it refers to bad input formats or security checks (like an input array with a maxLength)
404 The server can not find the requested resource.
The ID format is valid and you can't find the resource in the data source.
If you don't follow any standard architecture, you should define how you want to manage these cases and share your thought with the team and customers.
In many legacy applications, an HTTP status 200 with errors field is very common since very-old clients were not so good to manage errors.

HTTP status code response when there is not matched data with DB

I am building an API about email auth code.
Its process is simple.
input random code (client browser)
request with input code. (client browser)
receive the request (server)
scan the code from DB (server)
there is no code matched (server)
return a response with status code.
There are many status code, (2xx, 4xx, 5xx);
but I don't know which status code number is the most proper for this case.
It depends on the semantics you want to give your request. E.g.:
The API should search for items matching the query and return a list of results, like GET /codes?q=4ba69g. Think a "search page". In this case, an empty result [] is a perfectly valid result; nothing was wrong with the query, it just didn't return any matches. That's a 200 OK, or maybe a 204 No Content if you want to omit the empty response body entirely.
The code is treated like a resource, e.g. GET /codes/4ba69g. In this case a missing code would result in a 404 Not Found.
It's an action you want to perform which may fail, e.g. POST /login. If the user supplied the wrong credentials/code and hence the action cannot complete, that's a client-side error and therefore a 400 Bad Request.

How to set http response code in Parse Server cloud function?

A parse server cloud function is defined via
Parse.Cloud.define("hello", function(request, response) {..});
on the response, I can call response.success(X) and response.error(Y), and that sets the http response code and the body of the response.
But how do I define a different code, like created (201)?
And how do I set the headers of the response?
thanks, Tim
You are allowed to return any valid JSON from response.success(). Therefore, you could create an object with fields such as code, message, and value, so you can set the code, give it a string descriptor, and pass back the value you normally would, if there is one. This seems to accomplish what you need, though you will have to keep track of those codes across your platforms. I recommend looking up standard http response codes and make sure you don't overlap with any standards.

Getting a HTTP Status code 404 on web_custom_request in Loadrunner

I have a web_custom_request method that needs to handle dynamic item data
web_custom_request("create",
"URL=someurl\create",
"Method=POST",
"Resource=0",
"RecContentType=application/json",
"Referer=someurl",
"Snapshot=t6.inf",
"Mode=HTML",
"EncType=application/json",
"Body={\"actions\":{\"name\":\"value\"}}"
LAST);
To address the dynamic name-value pair parameters that come into play, I had built a bufferthat would hold the Body string. I have used correlation and looping to achieve that. Code towards the end of building this buffer looks like this
lr_param_sprintf("s_buffer", "\\\"actions\\\":{%s}",paramStr);
lr_output_message("Final Actions string is %s", lr_eval_string("{s_buffer}"));
Output for above lr_output_message is
Final Actions string is \"actions\":{\"name\":\"value\"}
I replaced Body parameter in web_custom_request with the buffer I had built
web_custom_request("create",
"URL=someurl\create",
"Method=POST",
"Resource=0",
"RecContentType=application/json",
"Referer=someurl",
"Snapshot=t6.inf",
"Mode=HTML",
"EncType=application/json",
"Body={s_buffer}"
LAST);
I receive a HTTP Status-Code=400 (Bad Request) indicating the format of web_custom_request is wrong. I would highly appreciate if someone could help me with the Body parameter so that the web_custom_request embraces it like the way it should.
Record it three times. First two with the same login session. The third with another one. You likely have something that is going to change based upon data which is not being handled in the body appropriately.

wcf message response parameter

I've read this example http://msdn.microsoft.com/en-us/library/ee476510.aspx about dynamic responses in wcf.
The sample on the bottom fit my goal pretty well. This is what i did:
[OperationContract]
[WebGet(UriTemplate = "/salaries({queryString})")]
Message GetSalaryByQuery(string queryString);
and my GetSalaryByQuery-Method:
public Message GetSalaryByQuery(string querystring)
{
if (WebOperationContext.Current.IncomingRequest.Accept == "application/json")
return WebOperationContext.Current.CreateJsonResponse<Result>(Salary.GetSalaryByQueryJson(querystring));
else
return WebOperationContext.Current.CreateAtom10Response(Salary.GetSalaryByQuery(querystring));
}
It is pretty similiar to the example i found.
But its not working however. It says that there is another parameter besides the message. I googled the message-class and it seems to me that its not possible to add an parameter to a message-response.
Is there a way to pass a parameter with the request and get a response with a message object?
Is there another way to get the dynamic response?
Thanks in advance.
I got it to work. I just deleted the Metadata-Enpoint and the behavior. My Webservice provides metadata on its own and therefore doesnt need to have the mex-Metadata defined.