Reputation: 5218
I have a HTTP function that returns a status code, but I also want to bind output to a blob. But when the request is not valid, I don't want to create the output blob at all. I tried something like:
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "{userName}/messages")] HttpRequest req,
string userName,
[Blob("users/{userName}/{DateTime}.json", FileAccess.Write)] Stream outputStream)
{
if (IsValid(req.Body))
{
await req.Body.CopyToAsync(outputStream);
return new AcceptedResult();
}
else
{
return new BadRequestResult();
}
}
But, unfortunately, the output blob is always created, even when the BadRequest
is returned. (The file created is blank, but I don't want it created at all.)
I also tried settting outputStream = null
right before the BadRequest
is returned, but that didn't help.
Is there a way to conditioanl create the blob file?
Upvotes: 2
Views: 465
Reputation: 20067
In blob function, when the {DateTime}.json
is not exist in the container, it will create the blob automatically. So, if you were to set your output blob path to users/{userName}/{DateTime}.json
the system will automatically generate a new datetime.json file for you so that the output blob is always created.
So, you could use the following code to conditional create the blob file.
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "{userName}/messages")] HttpRequest req,
string userName,
[Blob("users/{userName}", Connection = "StorageConnectionString")] CloudBlobContainer outputContainer)
{
if (IsValid(req.Body))
{
await outputContainer.CreateIfNotExistsAsync();
var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var blobName = DateTime.Now.ToString() + ".json";
var cloudBlockBlob = outputContainer.GetBlockBlobReference(blobName);
await cloudBlockBlob.UploadTextAsync(requestBody);
return new AcceptedResult();
}else{
return new BadRequestObjectResult("bad request");
}
}
Upvotes: 1