Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 发布后服务器端请求后数据读取间歇性失败_C#_Ajax_Post_Recaptcha - Fatal编程技术网

C# 发布后服务器端请求后数据读取间歇性失败

C# 发布后服务器端请求后数据读取间歇性失败,c#,ajax,post,recaptcha,C#,Ajax,Post,Recaptcha,我有一个从Javascript代码到C#Web Api的Ajax请求,在实际处理请求之前,我试图验证reCaptcha信息。当我从VS2015社区(localhost:port/下的IIS Express)对其进行本地测试时,效果非常好,但当我将其部署到测试服务器(机器/文件夹下的单独机器上的IIS)或甚至本地测试IIS(在localhost中,但在LocahHost/folder/下)时,请求失败,代码为500,因此我得到了自己的“服务器错误”信息 这是我的API方法 [HttpPos

我有一个从Javascript代码到C#Web Api的Ajax请求,在实际处理请求之前,我试图验证reCaptcha信息。当我从VS2015社区(localhost:port/下的IIS Express)对其进行本地测试时,效果非常好,但当我将其部署到测试服务器(机器/文件夹下的单独机器上的IIS)或甚至本地测试IIS(在localhost中,但在LocahHost/folder/下)时,请求失败,代码为500,因此我得到了自己的“服务器错误”信息

这是我的API方法

    [HttpPost]
    public List<Thing> GetThings(string parameter1, string parameter2)
    {
        List<Thing> ListThings = new List<Thing>();
        try
        {
            var serializer = new JsonSerializer();
            bool recaptchaValidation = false;
            using (var sr = new StreamReader(Request.Content.ReadAsStreamAsync().Result))
            {
                using (var jsonTextReader = new JsonTextReader(sr))
                {
                    dynamic captchaResponse = serializer.Deserialize(jsonTextReader, typeof(ReCaptchaEncodedResponse));
                    recaptchaValidation = ReCaptcha.ReCaptcha.Validate(captchaResponse.captchaResponse, System.Configuration.ConfigurationManager.AppSettings["recaptchaPrivateKey"]) == "True" ? true : false;
                }
            }
            if (!recaptchaValidation)
                return null;
         ... Code for getting the list of things...
         return ListThings;
         }
         ... Code for processing exceptions ... 
    }
这是我的ReCaptchaEncodedResponse类

public class ReCaptchaEncodedResponse
{
    public string captchaResponse { get; set; }
}
我不确定,但我开始相信问题出在POST参数(在我读到的body中)和服务器中的Request.Content之间

那怎么了


更新:更改了API方法,使其仅从post接收所有信息,并删除了丑陋的阅读请求正文

修改API方法:

    public List<Thing> GetThings([FromBody]SearchRequest srequest)
    {
        List<Thing> ListThings = new List<Thing>();
        bool recaptchaValidation = false;
        recaptchaValidation = ReCaptcha.ReCaptcha.Validate(srequest.ValidationToken, System.Configuration.ConfigurationManager.AppSettings["recaptchaPrivateKey"]) == "True" ? true : false;
        if (!recaptchaValidation)
            return null;
       ...
     }
参数类:

public class SearchRequest {
        public string Param1 { get; set; }
        public string Param2 { get; set; }
        public string ValidationToken { get; set; }
    }

再次像VS2015 IIS Express中的符咒一样工作,本地IIS出现错误500。

已解决

这个错误(像往常一样)来自一个最意想不到、最愚蠢、最简单的地方,在那里你几乎从不检查

这两个代码都工作正常,但我忘记设置代理,让服务器连接到Google,以验证令牌

请参阅,第一个对Google的请求来自客户端(javascript代码),因此它使用浏览器的代理设置,这些设置通常是正确的。现在,第二个请求来自服务器(C#代码),因此它将使用服务器的配置和凭据进行连接

使用本地IIS Express进行测试时也使用与客户端相同的配置,因为IIS Express在记录的用户凭据和配置上运行。但是标准IIS本身通常使用自己的用户凭据运行,因此没有代理配置

修改(并工作!)代码

就这样,萨约娜拉

$scope.submitForm = function () {
    $scope.captchaResponse = grecaptcha.getResponse();
    if (!$scope.captchaResponse) {
        alert("Captcha verification required");
        return;
    }
    $("input").prop('disabled', 'disabled');
    var requestData = {
        Param1: $scope.Thing.Param1,
        Param2: $scope.Thing.Param2,
        ValidationToken: $scope.captchaResponse
    };
    $http.post('api/ManageThingsApi/GetThings',
                requestData, 'json').success(function (data) {
        if (data === null) {
            grecaptcha.reset();
            alert("Not found");
        }
        else if (data.length === 0) {
            grecaptcha.reset();
            alert("Not found");

        }
        else {
            $scope.Data = data;
            $location.path('/ShowThings');
            $("#Search").css({ 'display': "none" });

        }
        $("input").prop('disabled', '');
        }).error(function (error) {
            $("input").prop('disabled', '');
            alert("Server error");
    });
};
public class SearchRequest {
        public string Param1 { get; set; }
        public string Param2 { get; set; }
        public string ValidationToken { get; set; }
    }
    [HttpPost]
    public List<Thing> GetThings(ValidatedRequest requestParams)
    {
        List<Thing> ListThings = new List<Thing>();
        if (requestParams == null)
            throw new UnauthorizedAccessException("Unauthorized");
        if (string.IsNullOrEmpty(requestParams.ValidationToken))
            throw new UnauthorizedAccessException("Unauthorized");
        JObject obj = null;
        try
        {
            var wc = new WebClient();
            var googleVerificationURL = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}&remoteip={2}", ConfigurationManager.AppSettings["gReCaptchaPrivateKey"], requestParams.ValidationToken, remoteIpAddress);
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ProxyAddress"].Trim()))
            {
                wc.Proxy = new WebProxy(ConfigurationManager.AppSettings["ProxyAddress"].Trim());
                wc.Proxy.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ProxyUsername"].Trim(), ConfigurationManager.AppSettings["ProxyPassword"]);
            }
            var result = wc.DownloadString(googleVerificationURL);
            wc.Dispose();
            obj = JObject.Parse(result);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("Failed to connect to reCaptcha", ex);
        }
        if(obj == null || !(bool)obj.SelectToken("success"))
            throw new UnauthorizedAccessException("Unauthorized");
        ... Rest of the code ... 
     }
    public class ValidatedRequest
    {
        public string ValidationToken { get; set; }
        public string Data1 { get; set; }
        public string Data2 { get; set; }
    }