首页 > 解决方案 > HttpRequestMessage.CreateResponse 抛出 StackOverflowException

问题描述

我有一个功能应用程序。我写了一个单元测试项目(xunit)来测试我的函数应用代码。在单元测试方法中,我正在调用我的函数应用程序的Run方法。当请求为“获取”时,我的函数应用程序返回一个简单的 json 对象。虽然这在我的机器上运行良好,但在我同事的所有机器中,以下行都在抛出StackOverFlowException. 当我检查异常详细信息时,StackTrace为空。

request.CreateResponse(HttpStatusCode.OK, jObject)

在调试窗口中,我看到错误为“System.private.corlib.dll 中发生未处理的异常”

功能应用:

     public static async Task<HttpResponseMessage> Run(
                      [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, ILogger log)
             {
                if (req.Method.Method.Equals(HttpMethod.Get.Method))
                {
                   NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(req.RequestUri.Query);
                   operation = queryString.Get("operation");
                
                    if (operation == "GetVersion")
                    {
                       version = VersionHistory.GetVersion("ABC");// returns 
                                                               // {"ABC" : "2.1"}
                       return req.CreateResponse(HttpStatusCode.OK, version);  
                                  //Above line causes StackOverFlowException
                     }
                     else
                     {
                       return 'Error message'
                      }
                 }
             }

上面代码中的VersionHistory只是我正在使用的一个静态类。它只是返回一个类似于 {{"ABC": "0.1.2"}} 的 json 对象。它与 .net 框架版本无关。

public static JObject GetVersion(string key)
       {
            // some logic. This logic is hit only once. I'm sure this is not 
           // causing any exception
            return JObject.Parse("{\"" + key + "\":\"0.1.2\"}");
        }

单元测试:

    public async Task Run_WhenGetRequest_ShouldReturnAppropriateFunctionAppVersion()
            {
                const string QUERYSTRING_KEY = "operation";
                const string QUERYSTRING_VALUE = "GetVersion";
                const string FUNCTION_APP_NAME = "ABC";
                const string FUNCTION_APP_VERSION = "2.1";
    
                _request.Method = HttpMethod.Get;
                NameValueCollection queryList = HttpUtility.ParseQueryString(_request.RequestUri.Query);
                if (queryList.Get(QUERYSTRING_KEY) == null)
                {
                    string queryString = QueryHelpers.AddQueryString(_request.RequestUri.ToString(), QUERYSTRING_KEY, QUERYSTRING_VALUE);
                    _request.RequestUri = new System.Uri(queryString);
                }
    
                HttpResponseMessage response = await FunctionAppClassName.Run(_request, _logger);

                // Assert code
            }

我在 Fixture 类中构造了请求对象,如下所示并模拟了 Logger 实例。

    Request = new HttpRequestMessage
                {
                    Content = new StringContent("", Encoding.UTF8, "application/json"),
                    RequestUri = new Uri("http://localhost/")
                };
    
                var services = new ServiceCollection().AddMvc().AddWebApiConventions().Services.BuildServiceProvider();
    
                Request.Properties.Add(nameof(HttpContext), new DefaultHttpContext { RequestServices = services });

知道如何解决这个问题吗?

标签: c#stack-overflowxunit.net.net-core-3.1httpresponsemessage

解决方案


最后我们发现了问题。问题是当我们从测试用例调用 Http 触发函数应用程序时,它无法找到 MediaType。在像下面这样添加媒体类型作为响应后,它起作用了。

    return req.CreateResponse(HttpStatusCode.OK, jObject, "application/json");

我仍然不确定为什么这个问题只出现在 Visual Studio 2019 16.6.x 和 16.7.x 中,而不是 16.4.x 中。如果有人能对此有所了解,我们将不胜感激

感谢那些付出时间的人。


推荐阅读