I have the problem, that I can't retrieve the body of a POST statement of a JSON Object. Here is the function, which is called when executing the http-Request:
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "HttpTriggerCSharp/name/{name}")]HttpRequestMessage req, string name, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string output = JsonConvert.SerializeObject(req.Content.ToString());
// Fetching the name from the path parameter in the request URL
return req.CreateResponse(HttpStatusCode.OK, output);
}
Im executing the POST with Postman and the following URL: http://localhost:7071/api/HttpTriggerCSharp/name/test
In the Header I wrote "Content-Type: application/json" and the Body looks like this:
{
"Benutzer":"Nenad",
"Passwort":"test"
}
My result is this: "\"System.Net.Http.StreamContent\""
Thank you for your help!
Thanks for the answers guys,
i found now an other solution with the help of a friend, this is the following:
public static async System.Threading.Tasks.Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "HttpTriggerCSharp/name/{name}")]HttpRequestMessage req, string name, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
dynamic dataArray = await req.Content.ReadAsAsync<object>();
string output = dataArray.ToString();
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Benutzer>(output);
// Fetching the name from the path parameter in the request URL
return req.CreateResponse(HttpStatusCode.OK, data);
}
Content is an instance of HttpContent class (as you can see in your output). So you have to use an appropriate method to get the string.
Related
What are the first steps for creating a azure function to get the data from my sql database
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $"Hello, {name}. This HTTP triggered function executed successfully.";
return new OkObjectResult(responseMessage);
I have created an Azure Function which connects to an API. This is the code:
public static async Task<HttpResponse> RunProduction(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
_log = log;
API_URL = #"{API_URL}";
BEARER_TOKEN = Environment.GetEnvironmentVariable("{ENV_NAME}");
if (BEARER_TOKEN.Equals("")) throw new Exception("Bearer token could not be retrieved");
var response = req.HttpContext.Response;
response.Clear();
response.StatusCode = 200;
response.ContentType = "text/plain";
//This is where the API will be called.
//The method is not changing anything in the response (yet)
response = await ExecuteMethods(req, response);
return response;
}
I am testing the Function locally with Postman. In Postman, I have the following headers:
Every time I test the Function, I receive a 406 Not Acceptable. This even happens when I comment the line where the method ExecuteMethods() is being called.
Any ideas how I can get rid of the 406-error and get my 200-statuscode again?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Something is just wrong here and I can't figure it out.
I am POSTing to an Azure Function in Visual Studio 2019/c# in debug. The POST looks like this:
In debug, the requestBody is grabbed from the stream and put into a string. I am deserializing the JSON into an object (I've tried dynamic as well) but the object is not populated. In fact, the object "data" doesn't even seem to exist. See the image where I am at a breakpoint and the value "data" doesn't even exist:
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string requestBody = String.Empty;
using (StreamReader streamReader = new StreamReader(req.Body))
{
requestBody = await streamReader.ReadToEndAsync();
}
var data = JsonConvert.DeserializeObject<AppInfo>(requestBody);
string responseMessage = string.IsNullOrEmpty(data.UserGuid) ? "User not logged" : "User logged";
return new OkObjectResult(responseMessage);
}
public class AppInfo
{
public string AppName = "";
public string UserGuid = "";
}
I am using below code I can get the Json deserialize object. Please check below
I tried with both dynamic and Var datatype to store the json deserialize object
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var data = JsonConvert.DeserializeObject<AppInfo>(requestBody as string);
var val = JsonConvert.SerializeObject(data);
string responseMessage = string.IsNullOrEmpty(data.UserGuid) ? "User not logged" : "User logged";
return new OkObjectResult(responseMessage);
}
public class AppInfo
{
public string AppName = "";
public string UserGuid = "";
}
This wasn't a code issue, but a problem with Visual Studio.
This was a part of a bigger project. The other project I was going to send to release but decided to add some additional functionality. I had changed the build to "release" and then added this code. It wasn't able to run this code properly for whatever reason until I set the build type to "debug" - then the code started working properly.
I have created and HTTP Triggered Azure Function (v2) using .NET Core with the hopes that I can execute the function while passing in some info in the request body and then have the function return/download a file in the browser. Unfortunately I am struggling to get this working.
Below is a snippet of Code
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, ILogger log)
{
string csv;
//Do some stuff to create a csv
byte[] filebytes = Encoding.UTF8.GetBytes(csv);
req.HttpContext.Response.Headers.Add("content-disposition", "attachment;filename=Export.csv");
req.HttpContext.Response.ContentType = "application/octet-stream";
return (ActionResult)new OkObjectResult(filebytes);
}
When I do a post using Postman the request is accepted but the response is 406 "unacceptable" and the output in the log states
"Microsoft.AspNetCore.Mvc.Infrastructure.DefaultOutputFormatterSelector[1]
No output formatter was found for content type 'application/octet-stream' to write the response."
I've tried multiple content types including text/plain and text/csv, all give the same response about output formatting.
If I remove or comment out the ContentType the request processes and returns a 200 but the filebytes are returned in the response body instead of being downloaded in the browser.
You'll need a FileContentResult for this:
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, ILogger log)
{
string csv;
//Do some stuff to create a csv
byte[] filebytes = Encoding.UTF8.GetBytes(csv);
return new FileContentResult(filebytes, "application/octet-stream") {
FileDownloadName = "Export.csv"
};
}
While the comments correctly point out that the ideal solution is to kick off processing in the HTTP function asynchronously, return a 202 Accepted response, save the result to blob storage, have the client wait for processing to complete before starting the blob download and then delete the blob once it's been downloaded, current Azure Functions pricing is only $0.000016/GB-s so you may find that to be unnecessarily complicated unless you have quite high traffic.
If have a simple HTTP triggered function in C# which just doesn't return the result:
public static HttpResponseMessage Run(HttpRequestMessage req, TraceWriter log)
{
string jobId = req.Headers.GetValues("scheduler-jobid").FirstOrDefault();
string executionTime = req.Headers.GetValues("scheduler-expected-execution-time").FirstOrDefault();
return req.CreateResponse(HttpStatusCode.OK,new {
JobId = jobId,
ExecutionTime = executionTime}
);
}
I checked with POSTMAN that HTTP headers are set correctly but just get a 200 OK without a response body.
In hindsight the solution is obvious:
I had to define a HTTP Response output and without changing the code above the Azure Functions runtime automatically wires in the req.CreateResponse.