Microsoft.Azure.WebJobs.Script:无法将“System.String”类型的对象转换为“Microsoft.AspNetCore.Http.HttpRequest”类型。回

Posted

技术标签:

【中文标题】Microsoft.Azure.WebJobs.Script:无法将“System.String”类型的对象转换为“Microsoft.AspNetCore.Http.HttpRequest”类型。回来的时候【英文标题】:Microsoft.Azure.WebJobs.Script: Unable to cast object of type 'System.String' to type 'Microsoft.AspNetCore.Http.HttpRequest'. when return 【发布时间】:2020-12-22 17:52:11 【问题描述】:

我有一个用 JS 编写的 Azure 函数,它由服务总线触发并生成文件到 Blob 存储。当我尝试返回 HTTP 结果时,我收到如下错误:

System.Private.CoreLib: Exception while executing function: Functions.categoryMessageConsumer. Microsoft.Azure.WebJobs.Script: Unable to cast object of type 'System.String' to type 'Microsoft.AspNetCore.Http.HttpRequest'.

我不知道为什么结果试图映射到 HttpRequest 对象。

index.ts:

import  AzureFunction, Context, HttpRequest  from '@azure/functions';
...

const serviceBusTopicTrigger: AzureFunction = async function(context: Context, req: HttpRequest) 
    let categoryMessage: CategoryMessage = Object.assign(new CategoryMessage(), req);
    let messageValidationResult = await categoryMessage.validate();
    if(!messageValidationResult.isValid) 
        context.log.error(messageValidationResult.errors);
        return 
            status: 400,
            body: "Unexpected error"
        ;
    

    ...

function.json 输出绑定:

...
    
      "type": "http",
      "direction": "out",
      "name": "$return"
    
...

host.json


  "version": "2.0",
  "logging": 
    "applicationInsights": 
      "samplingSettings": 
        "isEnabled": true,
        "excludedTypes": "Request"
      
    
  ,
  "extensionBundle": 
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  

【问题讨论】:

【参考方案1】:
var http = require('https');
module.exports = function (context, eventHubMessages) 
    context.log(`javascript eventhub trigger function called for message array $eventHubMessages`);
    
    eventHubMessages.forEach((message, index) => 
        
        function callService(msg) 
            let promise = new Promise((resolve, reject) => 
                var options = 
                    host: process.env["HOST"],
                    port: process.env["PORT"],
                    path: process.env["PATH"],
                    method: process.env["WEBSERVICE_METHOD"],
                    headers: 
                        'Content-Type': process.env["WEBSERVICE_CONTENT_TYPE"],
                        'x-api-key' : process.env["WEBSERVICE_API_KEY"]
                    
                ;
                var response = '';
                const request = http.request(options, (res) => 
                    res.on('data', (d) => 
                        response += d;
                    )
    
                    res.on('end', (d) => 
                        context.res = 
                            body: response
                        ;
                        resolve(response);
                    )
                );

                request.on('error', (error) => 
                    context.log.error(error);
                    reject(error);
                    context.done();
                )
                
                request.write(msg);
                request.end();

              );
              promise.then((response) => 
                context.log(`mensagge send: $msg`);
                context.log(`response: $response`);
                context.done();
            );
            
        
        
        callService(message);
    );
;

这是我的 index.js

现在是我的 function.js:


  "bindings": [
    
      "type": "eventHubTrigger",
      "name": "eventHubMessages",
      "direction": "in",
      "eventHubName": "event-hub-name",
      "connection": "CONNECTION_EVENT_HUB",
      "cardinality": "many",
      "consumerGroup": "$Default",
      "dataType": "string"
    ,
    
      "type": "http",
      "direction": "out",
      "name": "$return"
    
  ]

在 local.settings.json 中,我声明了所有环境变量,如 HOST、PORT、CONNECTION_EVENT_HUB 等。

【讨论】:

【参考方案2】:

这是因为,您的函数可能正在尝试创建另一个它没有预料到的对象。

正如您提到的响应变量名称为$return 并且它是预期的。而不是这样,编码你的函数如下:

function.json:


    "disabled": false,    
    "bindings": [
        
            "authLevel": "function",
            "type": "httpTrigger",
            "direction": "in",
            "name": "req"
        ,
        
            "type": "http",
            "direction": "out",
            "name": "res"
        
    ]

JS 代码:

module.exports = function(context, req) 
    context.log('Node.js HTTP trigger function processed a request. RequestUri=%s', req.originalUrl);

    if (req.query.name || (req.body && req.body.name)) 
        context.res = 
            // status defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name)
        ;
    
    else 
        context.res = 
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        ;
    
    context.done();
;

function.json中的配置选项,您可以访问here和here。

【讨论】:

以上是关于Microsoft.Azure.WebJobs.Script:无法将“System.String”类型的对象转换为“Microsoft.AspNetCore.Http.HttpRequest”类型。回的主要内容,如果未能解决你的问题,请参考以下文章