I send a file via POST to my ApiController.
If the file is below 2 MB, everything works like a charm.
If the file is bigger, I get a Error 404.
This is the (old) function declaration in my Controller:
[HttpPost]
public HttpResponseMessage FileUpload(HttpRequestMessage req, string entryId = "", string owner = "", int debug = 0)
{
which returns, if the entity is too large, this:
Remote Address:172.17.41.12:443
Request URL:https://webdevserver/myapp/api/Debug/FileUpload
Request Method:POST
Status Code:404 Not Found
or if it is inside the size limits, this:
Remote Address:172.17.41.12:443
Request URL:https://webdevserver/myapp/api/Debug/FileUpload
Request Method:POST
Status Code:200 OK
So I want to send a useful error message - which Error 404 definitely is NOT! - and stumbled upon HTTP Status Code 413, which IIS doesn't send automatically :( so I changed my code to:
[HttpPost]
public HttpResponseMessage FileUpload(HttpRequestMessage req=null, string entryId = "", string owner = "", int debug = 0)
{
if(req==null) {
// POST was not handed over to my function by IIS
// now is it possible to check whether file was empty or too large!? Because
return new HttpResponseMessage(HttpStatusCode.RequestEntityTooLarge);
// should only be sent if POST content was really too large!
So, how can I check whether the size of the POST data was too big or POST was empty?
According to this blog, the status code 404.13 was introduced in IIS 7 to replace the http status code 413.
Since this was done by design, I would suggest that you maintain the response as is, and in your code try to determine whether the 404 error was actually a 404.13 error.
Related
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?
When a user uses a slash command, I post an ephemeral message to just that user. When they click a button I want that ephemeral message to either delete or update. Right now I'm just trying to get the delete part working.
In the Slack API documentation it says to send a HTTP POST to the response_url. The only response_url I get when a user clicks a button is something like this: https://hooks.slack.com/actions/XXXXXXXXX/YYYYYYYYYYYY/ZZZZZZZZZZZZZZZZZZZZZZZZ
When I send a POST to that url, I get an error(I'm not sure what the error is, I just know that my code fails on a try/catch).
The JSON I'm sending to that URL looks like this:
{
"response_type" = "ephemeral",
"replace_original" = "true",
"delete_original" = "true",
"text" = ""
};
I see in the Slack API documentation it says I should be sending that JSON to a URL that begins with https://hooks.slack.com/services/ however I'm not receiving any response_url that has the /services/.
Here is the C# code I am using to send the response:
var replaceMsg = new NameValueCollection();
replaceMsg["delete_original"] = "true";
replaceMsg["replace_original"] = "true";
replaceMsg["response_type"] = "ephemeral";
replaceMsg["text"] = "";
var responseReplace = client.UploadValues(button.response_url, "POST", replaceMsg);
Edit: It looks like I'm getting a 404 error when I try to send that
Exception: System.Net.WebException: The remote server returned an error: (404) Not Found.
However, when I paste the exact URL into my browser I don't get a 404, I see a JSON.
Can anyone guide me in the right direction? Thanks.
I did something very similar not too long ago and was able to get it working, though it was tricky.
This post helped me big time: How to remove Ephemeral Messages
I would do two things:
1) make sure you know what that POST response failure is as it may contain useful information.
2) It looks like you're sending in the string "true" instead of the boolean values, I'm guessing you probably want to send the boolean values instead:
{
"response_type" = "ephemeral",
"replace_original" = true,
"delete_original" = true,
"text" = ""
};
#theMayer and #Aaron were correct about the headers being wrong.
Setting the headers solved the issue, like so:
var client = new WebClient();
client.Headers.Add("Content-Type", "text/html");
var response = client.UploadData(button.response_url, "POST", Encoding.Default.GetBytes("{\"response_type\": \"ephemeral\",\"replace_original\": \"true\",\"delete_original\": \"true\",\"text\": \"\"}"));
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.