BlobClient - What is the recommended way to check if my upload was successfull? - azure-blob-storage

The Azure blob client's Upload method returns a Response<BlobContentInfo>.
If the upload throws an exception, than something is wrong, that's clear.
Failure cases, like bad connection string or no internet connection does throw an exception. And it retries by default.
But if I do get a Response back, can still something be wrong?
On the BlobContentInfo I see no indicator of any error.
The Response has a GetRawResponse method, and there is a IsError bool flag on that, and a Status for HTTP status code. But no specific description if something goes wrong.
Maybe check for IsError, and try to log the response, if it's true, and assume it did work, if there is no error. And check the ContentHash I guess.

But if I do get a Response back, can still something be wrong?
No. It would mean what you were trying to upload got uploaded successfully.
If your upload fails, the method will raise an exception of type RequestFailedException.

Related

Forbid() returns 404

I have returned Forbid() from a web request, and the browser claims its receiving a 404 instead of a 403.
I have added a handler to the cookie authentication like so...
o.Events.OnRedirectToAccessDenied += ctx =>
{
ctx.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return Task.FromResult(0);
};
But this doesn't appear to be called.
Thus, why is a method that should return a 403 returning a 404?
I had the same issue. These were my steps to fix it:
Temporarily remove all the exception handling like app.UseExceptionHandler("/Home/Error") from Startup. In my case the 404 happened because the exception handling was broken.
Then I got the "real" error: My problem was that I had no authentication configured, and therefore no authentication schemes.
After I added the correct authentication options to Startup (in my case I used a custom authentication handler) I got the correct response code:
services.AddAuthentication(LicenseKeyAuthenticationOptions.Scheme)
.AddScheme<LicenseKeyAuthenticationOptions, LicenseKeyAuthenticationHandler>(LicenseKeyAuthenticationOptions.Scheme, null);
The Forbid() command seems to have an internal ASP.NET MVC controller redirect handling. In case you only want to provide a classic API and want 403 to be returned you should switch the command to
return StatusCode(StatusCodes.Status403Forbidden);
Don't forget to import the using
using static Microsoft.AspNetCore.Http.StatusCodes;
Source: https://stackoverflow.com/a/47708867/828184
So far I'm not aware if this behaviour of Forbid() could be changed.

Accessing API layer

I am trying to access an api function, for example I want to access the login function, I get the following error:
"message": "An internal error occurred during your request!",
Looking in the log file, the following log is there:
ERROR 2017-10-09 17:01:37,296 [11 ]
nHandling.AbpApiExceptionFilterAttribute - Processing of the HTTP
request resulted in an exception. Please see the HTTP response
returned by the 'Response' property of this exception for details.
System.Web.Http.HttpResponseException: Processing of the HTTP request
resulted in an exception. Please see the HTTP response returned by the
'Response' property of this exception for details.
I am using Postman to test. My URL is https://localhost:44347/api/Account/Authenticate. My header has Context-Type as "application/json" and in my Body I have the loginModel formatted as
{
"tenancyName": "tenantname",
"userNameOrEmailAddress": "admin",
"password": "123qwe"
}
Am not sure how else to proceed on this. Any ideas please? I have swagger installed as well.
I am using MVC + AngularJS template. I have not changed anything, just the default project.
Appreciate the assistance.
I have tested with Fiddler and it works correctly.
Note: make sure you type Content-Type correctly, on the question you typed Context-Type
Make a POST request! You may be missing this.

Should I check if file exists before responding via .sendFile()?

Say I have this route handler in my Express.js app:
app.get('/files/:name', function (req, res) {
res.sendfile('path/to/files/' + req.params.name + '.html');
});
This path is used via Ajax on my site. I wonder if I should guard against situations where a file with the requested name does not exist on the server, in which case the server returns a 404 response. I can work with this, i.e. detect the 404 in the browser and act accordingly (e.g. display a message to the visitor). However, I'm not sure if this is a good approach. Is it OK to use the 404 response here, or am I supposed to try to avoid 404 responses if possible. (E.g. I could if a file with the requested name exists on the server and only use .sendFile() if it does.)
I'm worried that performing a manual check would only slow things down as .sendFile() already has this check built-in (i.e. it's possible to avoid this check and instead detect 404 responses in the browser which is what I'm doing right now and it works fine).
I would stick with returning a 404 instead, as that's the 404's purpose.I'm not sure there really is any other common/practical alternative.
Good luck.

ApiController accept the json in POST on the localhost testing server, but not on the production server. Why?

I have been struggling with this for two days. It is so discouraging.
It is a relatively simple api controller:
[HttpPost]
public HttpResponseMessage Save(ReportCreateInputModel model)
{
if (ModelState.IsValid)
{
_service.AddReport(model);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, model);
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
Everything works fine when debugging on localhost:xxxx. The model is valid and a new record can be inserted into the database.
But when it is published to the server, I always get a 400: Bad Request. I have tried different browser and am pretty sure it is a server side issue.
Then I tried increase the request size as mentioned in some other posts. But it still cannot work. I could not install remote debugging tool on that server.
Has anyone seen this problem before? Is it something with IIS 6?
I really appreciate any assistance. Thank you!
Update:
It turns out the api POST action is never hit before the Bad Request error is thrown. But why it is fine in local debugging?
Update:
I have added these lines of code in WebApiConfig.cs
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
json.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
Now in the jqXHR.responseText I have an exception
"$id":"3","Message":"An error has occurred.",
"ExceptionMessage":"This operation requires IIS integrated pipeline mode.",
"ExceptionType":"System.PlatformNotSupportedException",
"StackTrace":" at System.Web.HttpContext.get_CurrentNotification()
at System.Web.HttpContextWrapper.get_CurrentNotification()
at GetCurrentNotification(Object )
at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
Wow! Is it something to do with IIS 6 I am using? Who can tell me what that StackTrace is? Thanks.
Now I find out in here that it is get_CurrentNotification that requires the pipeline thing, which exists only in IIS7. But who can tell us where have I made calls to HttpContext.CurrentNotification?
Try changing the code to this instead to see why you are getting a bad request,
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
You should always include ModelState in your response if you are returning a 400 due to invalid ModelState. That way the clients would have information on what is wrong with their request.
Also, if possible, just for debugging, enable IncludeExceptionDetails always by doing this on your configuration. That way you can get more details in your 400 error response.
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
Remember that you should IncludeExceptionDetails always only for debugging on production servers. Otherwise, you would be leaking security sensitive information to everyone who can access your service which is bad.

NETWORK_ERROR: XMLHttpRequest Exception 101

I am getting this Error
NETWORK_ERROR: XMLHttpRequest Exception 101
when trying to get XML content from one site.
Here is my code:
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
if (xmlhttp==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
xmlhttp.onReadyStateChange=function() {
if(xmlhttp.readyState==4) {
var value =xmlhttp.responseXML;
alert(value);
}
}
xmlhttp.open("GET",url,false);
xmlhttp.send();
//alert(xmlhttp.responseXML);
}
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
Does any one have a solution?
If the url you provide is located externally to your server, and the server has not allowed you to send requests, you have permission problems. You cannot access data from another server with a XMLHttpRequest, without the server explicitly allowing you to do so.
Update: Realizing this is now visible as an answer on Google, I tried to find some documentation on this error. That was surprisingly hard.
This article though, has some background info and steps to resolve. Specifically, it mentions this error here:
As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work. Otherwise, an INVALID_ACCESS_ERR exception is thrown
An interpretation of INVALID_ACCESS_ERR seems to be what we're looking at here.
To solve this, the server that receives the request, must be configured to allow the origin. This is described in more details at Mozilla.
The restriction that you cannot access data from another server with a XMLHttpRequest can apply even if the url just implies a remote server.
So:
url = "http://www.myserver.com/webpage.html"
may fail,
but:
url = "/webpage.html"
succeed - even if the request is being made from www.myserver.com
Request aborted because it was cached or previously requested? It seems the XMLHttpRequest Exception 101 error can be thrown for several reasons. I've found that it occurs when I send an XMLHttpRequest with the same URL more than one time. (Changing the URL by appending a cache defeating nonsense string to the end of the URL allows the request to be repeated. -- I wasn't intending to repeat the request, but events in the program caused it to happen and resulted in this exception).
Not returning the correct responseText or responseXML in the event of a repeated request is a bug (probably webKit).
When this exception occurred, I did get an onload event with readyState==4 and the request object state=0 and responseText=="" and responseXML==null. This was a cross domain request, which the server permits.
This was on an Android 2.3.5 system which uses webKit/533.1
Anyone have documentation on what the exception is supposed to mean?
Something like this happened with me when I returned incorrect XML (I put an attribute in the root node). In case this helps anyone.
xmlhttp.open("GET",url, true);
set the async part to true
I found a very nice article with 2 diferent solutions.
The first one implementing jQuery and JSONP, explaining how simple it is.
The second approach, it's redirecting trough a PHP call. Very simple and very nice.
http://mayten.com.ar/blog/42-ajax-cross-domain
Another modern method of solving this problem is Cross Origin Ressource Sharing.
HTML5 offers this feature. You can "wrap" your XMLhttp request in this CORS_request and
if the target browser supports this feature, you can use it and wont have no problems.
EDIT:
Additionaly i have to add that there are many reasons which can cause this Issue.
Not only a Cross Domain Restriction but also simply wrong Settings in your WEB.CONFIG of your Webservice.
Example IIS(.NET):
To enable HTTP access from external sources ( in my case a compiled Phonegap app with CORS request ) you have to add this to your WEB.CONFIG
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Another scenario:
I got two webservices running... One on Port 80 and one on Port 90. This also gave me an XML HTTP Request Error. I even dont know why :). Nevertheless i think this can help many not well experienced readers.

Resources