I want to place a customer description for HTTP Status Code instead of using its default description. For example, the below image returned "403 Forbidden". I want to change it to "403 Unexpected Error" without body's content. The same go to Status Code 204 which my program expect a custom description.
Current Result
Here is my code:
[HttpPost("riskProfile")]
public async Task<IActionResult> CustomerRiskProfile([FromBody] CustomerRiskProfileRequest request)
{
var response = await _mediator.Send(request);
if(response.Code == Result.Forbidden.Value)
{
return StatusCode(403, string.Empty);
}
return StatusCode(204, string.Empty);
}
Do you guys have any idea to make the app display the intended result? Thank you in advance.
These http status codes are an RFC standard. These codes have a fixed meaning. According to https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages the response status line transmits the status code and message. I do not know a way in .net core web api to change the text for a code.
But better consider reading the status code in your front end app and then show a localized message appropriate for the status code. That's a better way. Or what is your motive?
Related
As the title says I am wondering if it possible to return information from the controller based on the success of the PUT request.
In this case I am using the put request to use my email service to send emails. Is there a way to return a results object that lists the statuses for each email so I can display on the front end which emails failed and why?
Thanks in advance for any advice.
Ideally PUT request(successful) is used to:
1.) Update an existing resource -200 OK with NO response body
2.) Creation of new resource (If the Request-URI does not point to an existing resource, origin server can create the resource with that URI) - 201 Created with some meta data ,resource identifier in the response body.
So as per the recommendation ,it should not be returned in the response of PUT request and a subsequent GET call should be made to get the status of the emails.
Refer the HTTP specification :
RF2616 -https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6
My current idea was to get the number representations of the status codes and decide what to do based on those. However I'm hitting a roadblock of sorts.
When I'm checking browser requests in chrome there is this part to every response:
Request URL: SiteURL
Request Method: GET
Status Code: 200 OK //note this part
Remote Address: 127.0.0.1:8888
Referrer Policy: no-referrer-when-downgrade
When I do something like this:
var response = Task.Run(() => this.HttpClient.GetAsync($"some_link"));
string pageHtml = response.Result.Content.ReadAsStringAsync().Result;
string statusCode = response.Result.StatusCode.ToString();
I get just "OK" for a status code instead of "200 OK" when everything is fine.
Is there a way to get the number representation of a status code? I'm not sure how to work with the text versions at all since I've no idea what most of those would say, and also I'm not at all sure if there are OK status codes that would work. Is it possible to get a status code of something different than "OK" and still get the requested page? If the answer is "No" I guess that would solve my problems right than and there.
The ultimate idea is when I get a bad status code like 504, 502 (or possibly something different than a good status code) the program just retries the response every 5 minutes until the situation is fixed and continues working after that.
Given this code, the entry for a C# REST API,
protected HttpResponseMessage ProcessRequest()
{
HttpResponseMessage _response = null;
try
{
//request is processed.
object _obj = ExecuteEvent();
//response object is created with success status and response content is assigned in the required mediatype format.
_response = Request.CreateResponse(HttpStatusCode.OK, Constants.ServiceConstants.VALUE);
_response.Content = new StringContent(System.Web.Helpers.Json.Encode(_obj), Encoding.UTF8, Constants.ServiceConstants.MEDIATYPE);
}
catch
{
}
return _response;
}
Returning a 200 response for every request and just setting the content to the serialized JSON as above, is this the right or wrong way to go about this?
I would have thought that we definitely should not just be returning a 200 OK for every request.
This code will throw an exception in ExecuteEvent, let's say if the user is unauthorized, however, shouldn't we actually be telling the caller that their request is unauthorized?
You should send back an HTTP status based ok what happened in your method. If everything worked correctly, you send back an OK. If there is a failure, you should send back the appropriate status code.
For example, if ExecuteEvent throws a message indicating that the user is not authorized, you would send back an HTTP stays code of Forbidden (a 403).
You can see all of Microsft's status codes here and you can get a list of the numbers and what they mean here. Most of the time these two lists with correspond to each other, they are just organized a little differently.
Hope that helps.
I have a ASP.NET Web API, and I have been responding to request with this format,
[HttpPost]
[Route("")]
public HttpResponseMessage AlexaSkill()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
response.Content = new StringContent("put json here", Encoding.UTF8);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
return response;
}
and that has been working great. The issue is that there are certain situation where the requester does not expect a response. I cannot figure out how to not give a response to the requester who is posting to the url. How can I be able to return a response like a have above and also have the option to have the function not give a respons essentially acting as a void function?
You should always return a response. There's a status code 204 for when you don't want to send content in your response. From the spec:
10.2.5 204 No Content
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.
So your code could be something like this:
[HttpPost]
public HttpResponseMessage SomeMethod()
{
// Do things
return Request.CreateResponse(HttpStatusCode.NoContent);
}
Even a void method will return an HTTP status code to the client invoking the API. See this link
You'll probably need to ask for changes or another alternative to your client.
If you want to just terminate the request, try this:
HttpContext.Current.Response.End();
throw new Exception("Terminating request.");
It seems like a strange thing for an HTTP server to do, but if that's what you really need, give that a shot. If you follow by throwing an exception, then an error won't be sent to the client because you've already ended the response.
In my POST method in a Controller.cs, I have been writing only a single value into the database so far, so at the end I returned the status of the response with the following code:
var response = Request.CreateResponse<object>(HttpStatusCode.Created, iconOffset);
return response;
But now, I am writing two values into the database, and I would love to return the status of both at the end of the POST method, how do I do that? I tried the following:
var response = Request.CreateResponse<object>(HttpStatusCode.Created, HttpStatusCode.Created, iconOffset, tempOffset);
return response;
But didn't work.
You wouldn't return multiple http status codes to the browser.
You make a request for something, you get a response back - that response was either OK or another status code, there's no concept of multiple response codes.
If you need to elaborate with your response, return a model along with your status for whatever is consuming the endpoint, one example would be:
return Request.CreateResponse(HttpStatusCode.OK, new DatabaseUpdateResult(results));
If your application could accept/return json, then this could be consumed by the client.
You can't do that. The response code is the HTTP response code and there is only one. You could either split out the method into two endpoints or return a status that represents the state of the operation.
Your client should have no knowledge of what is going on behind the service (database, services, ...) so if you're posting something to that endpoint and semantically it gets created just return Created. If an error occurs you could return InternalServerError.
Here's a list of HTTP status codes you can use: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes