locked
Basic Azure function + HttpRequest RRS feed

  • Question

  • User1308732545 posted

    Hi All,

    I am very new to Azure .
    I am trying to write a basic Azure function

    namespace FunctionApp1
    {
        public static class Function1
        {
            [FunctionName("Function1")]
            public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
            {
                log.Info("C# HTTP trigger function processed a request.");
    
                // parse query parameter
                string name = req.GetQueryNameValuePairs()
                    .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                    .Value;
    
                if (name == null)
                {
                    // Get request body
                    dynamic data = await req.Content.ReadAsAsync<object>();
                    name = data?.name;
                }
    
                return name == null
                    ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
                    : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
            }
        }
    }

    It works fine as it is , but when I change the parameters to "HttpRequest"(so that I can pass 'Code' in querystring) instead of HttpRequestMessage
    the function throws error when I run it and this is the error I get 

    <ApiErrorModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Azure.WebJobs.Script.WebHost.Models">
    <Arguments xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" i:nil="true"/>
    <ErrorCode>0</ErrorCode>
    <ErrorDetails>
    Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Function1 ---> System.InvalidOperationException : Exception binding parameter 'req' ---> System.MissingMethodException : No parameterless constructor defined for this object. at System.RuntimeTypeHandle.CreateInstance(RuntimeType type,Boolean publicOnly,Boolean noCheck,Boolean& canBeCached,RuntimeMethodHandleInternal& ctor,Boolean& bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly,Boolean skipCheckThis,Boolean fillCache,StackCrawlMark& stackMark) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,Boolean skipCheckThis,Boolean fillCache,StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type,Boolean nonPublic) at System.Activator.CreateInstance(Type type) at async Microsoft.Azure.WebJobs.Extensions.Http.HttpTriggerAttributeBindingProvider.HttpTriggerBinding.CreateUserTypeValueProvider(HttpRequestMessage request,String invokeString) at async Microsoft.Azure.WebJobs.Extensions.Http.HttpTriggerAttributeBindingProvider.HttpTriggerBinding.BindAsync(Object value,ValueBindingContext context) at async Microsoft.Azure.WebJobs.Host.Triggers.TriggeredFunctionBinding`1.BindCoreAsync[TTriggerValue](ValueBindingContext context,Object value,IDictionary`2 parameters) End of inner exception at Microsoft.Azure.WebJobs.Host.Executors.DelayedException.Throw() at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstance instance,ParameterHelper parameterHelper,TraceWriter traceWriter,CancellationTokenSource functionCancellationTokenSource) at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??) at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??) End of inner exception at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??) at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsync(IFunctionInstance functionInstance,CancellationToken cancellationToken) at Microsoft.Azure.WebJobs.Host.Executors.ExceptionDispatchInfoDelayedException.Throw() at async Microsoft.Azure.WebJobs.JobHost.CallAsync(??) at async Microsoft.Azure.WebJobs.Script.ScriptHost.CallAsync(String method,Dictionary`2 arguments,CancellationToken cancellationToken) at async Microsoft.Azure.WebJobs.Script.WebHost.WebScriptHostManager.HandleRequestAsync(FunctionDescriptor function,HttpRequestMessage request,CancellationToken cancellationToken) at async Microsoft.Azure.WebJobs.Script.Host.FunctionRequestInvoker.ProcessRequestAsync(HttpRequestMessage request,CancellationToken cancellationToken,WebScriptHostManager scriptHostManager,WebHookReceiverManager webHookReceiverManager) at async Microsoft.Azure.WebJobs.Script.WebHost.Controllers.FunctionsController.<>c__DisplayClass3_0.<ExecuteAsync>b__0(??) at async Microsoft.Azure.WebJobs.Extensions.Http.HttpRequestManager.ProcessRequestAsync(HttpRequestMessage request,Func`3 processRequestHandler,CancellationToken cancellationToken) at async Microsoft.Azure.WebJobs.Script.WebHost.Controllers.FunctionsController.ExecuteAsync(HttpControllerContext controllerContext,CancellationToken cancellationToken) at async System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken) at async System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken) at async Microsoft.Azure.WebJobs.Script.WebHost.Handlers.WebScriptHostHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken) at async Microsoft.Azure.WebJobs.Script.WebHost.Handlers.SystemTraceHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken) at async System.Web.Http.HttpServer.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
    </ErrorDetails>
    <Id>a527ddc2-fee5-4b61-8e22-5a0d250a209c</Id>
    <Message>
    Exception while executing function: Function1 -> Exception binding parameter 'req' -> No parameterless constructor defined for this object.
    </Message>
    <RequestId>a180a182-1d97-4872-9638-8c60645cbf2d</RequestId>
    <StatusCode>InternalServerError</StatusCode>
    </ApiErrorModel>


    Could somebody please explain why can I not use HttpRequest?

     I want to basically use HttpRequest so that I can pass paramter called "code" in my querystring and use the code that has been passed to process something else 

    and my questring should look like this :

    http://localhost:7071/api/Function1?code=jdfssd

    Thanks in advance

    Tuesday, April 17, 2018 1:20 PM

Answers

  • User283571144 posted

    Hi gowrifor.net,

    According to your description, I guess this may related with azure function SDK version.

    My azure function version is 1.0.6.

    I suggest you could update the azure function version.

    If this solution still doesn't solve your issue, I suggest you could push your demo application on github or onedrive for us to download and test.

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 19, 2018 5:31 AM

All replies

  • User283571144 posted

    Hi gowrifor.net,

    As far as I know, if you want to use httprequest as the parameter, you should directly use req.Query to get the query string.

    More details, you could refer to below code sample:

            [FunctionName("Function1")]
            public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req, TraceWriter log)
            {
                log.Info("C# HTTP trigger function processed a request.");
    
                string name = req.Query["code"];
    
                string requestBody = new StreamReader(req.Body).ReadToEnd();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                name = name ?? data?.name;
    
                return name != null
                    ? (ActionResult)new OkObjectResult($"Hello, {name}")
                    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
            }


    Result:

     

    Best Regards,

    Brando 

    Wednesday, April 18, 2018 8:11 AM
  • User1308732545 posted

    Hi Brando ZWZ,

    Thanks for your reply ,This is what I was looking for.

    I tried doing the same as you  , But for some reason I get this error , could you please help

    {
        "id": "df434ca7-3099-4672-89a9-f2063fbde3a3",
        "requestId": "92d79a4a-534e-4c98-a418-d318291e9e4b",
        "statusCode": 500,
        "errorCode": 0,
        "message": "Exception while executing function: Function1 -> Exception binding parameter 'req' -> Cannot create an abstract class.",
        "errorDetails": "Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Function1 ---> System.InvalidOperationException : Exception binding parameter 'req' ---> System.MissingMethodException : Cannot create an abstract class.\r\n   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type,Boolean publicOnly,Boolean noCheck,Boolean& canBeCached,RuntimeMethodHandleInternal& ctor,Boolean& bNeedSecurityCheck)\r\n   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly,Boolean skipCheckThis,Boolean fillCache,StackCrawlMark& stackMark)\r\n   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,Boolean skipCheckThis,Boolean fillCache,StackCrawlMark& stackMark)\r\n   at System.Activator.CreateInstance(Type type,Boolean nonPublic)\r\n   at System.Activator.CreateInstance(Type type)\r\n   at async Microsoft.Azure.WebJobs.Extensions.Http.HttpTriggerAttributeBindingProvider.HttpTriggerBinding.CreateUserTypeValueProvider(HttpRequestMessage request,String invokeString)\r\n   at async Microsoft.Azure.WebJobs.Extensions.Http.HttpTriggerAttributeBindingProvider.HttpTriggerBinding.BindAsync(Object value,ValueBindingContext context)\r\n   at async Microsoft.Azure.WebJobs.Host.Triggers.TriggeredFunctionBinding`1.BindCoreAsync[TTriggerValue](ValueBindingContext context,Object value,IDictionary`2 parameters) \r\n   End of inner exception\r\n   at Microsoft.Azure.WebJobs.Host.Executors.DelayedException.Throw()\r\n   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstance instance,ParameterHelper parameterHelper,TraceWriter traceWriter,CancellationTokenSource functionCancellationTokenSource)\r\n   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)\r\n   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??) \r\n   End of inner exception\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)\r\n   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsync(IFunctionInstance functionInstance,CancellationToken cancellationToken)\r\n   at Microsoft.Azure.WebJobs.Host.Executors.ExceptionDispatchInfoDelayedException.Throw()\r\n   at async Microsoft.Azure.WebJobs.JobHost.CallAsync(??)\r\n   at async Microsoft.Azure.WebJobs.Script.ScriptHost.CallAsync(String method,Dictionary`2 arguments,CancellationToken cancellationToken)\r\n   at async Microsoft.Azure.WebJobs.Script.WebHost.WebScriptHostManager.HandleRequestAsync(FunctionDescriptor function,HttpRequestMessage request,CancellationToken cancellationToken)\r\n   at async Microsoft.Azure.WebJobs.Script.Host.FunctionRequestInvoker.ProcessRequestAsync(HttpRequestMessage request,CancellationToken cancellationToken,WebScriptHostManager scriptHostManager,WebHookReceiverManager webHookReceiverManager)\r\n   at async Microsoft.Azure.WebJobs.Script.WebHost.Controllers.FunctionsController.<>c__DisplayClass3_0.<ExecuteAsync>b__0(??)\r\n   at async Microsoft.Azure.WebJobs.Extensions.Http.HttpRequestManager.ProcessRequestAsync(HttpRequestMessage request,Func`3 processRequestHandler,CancellationToken cancellationToken)\r\n   at async Microsoft.Azure.WebJobs.Script.WebHost.Controllers.FunctionsController.ExecuteAsync(HttpControllerContext controllerContext,CancellationToken cancellationToken)\r\n   at async System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)\r\n   at async System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)\r\n   at async Microsoft.Azure.WebJobs.Script.WebHost.Handlers.WebScriptHostHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)\r\n   at async Microsoft.Azure.WebJobs.Script.WebHost.Handlers.SystemTraceHandler.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)\r\n   at async System.Web.Http.HttpServer.SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)"
    }

    Wednesday, April 18, 2018 9:19 AM
  • User283571144 posted

    Hi gowrifor.net,

    According to your description, I guess this may related with azure function SDK version.

    My azure function version is 1.0.6.

    I suggest you could update the azure function version.

    If this solution still doesn't solve your issue, I suggest you could push your demo application on github or onedrive for us to download and test.

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 19, 2018 5:31 AM
  • User1992938117 posted

    As Brando said, its SDK mismatch, use latest Azure SDK and dependent dlls.

    Similar issues is logged here:

    https://stackoverflow.com/questions/48478543/cannot-create-an-abstract-class 

    Thursday, April 19, 2018 10:01 AM
  • User1308732545 posted

    Thanks Brando, 

    It was indeed the SDK version issue, 

    Its resolved now .

    Many Thanks

    Thursday, April 19, 2018 10:12 AM