在调用Web.api时收到'方法不允许'错误'

时间:2016-04-05 09:38:42

标签: asp.net-mvc wcf rest asp.net-web-api2

在使用web.Api时,我不允许使用方法(405)。我遵循了所有步骤,但问题仍然存在。但是当我通过soapUi进行测试时效果很好。请帮忙

Web.Api宣言:

 [Route("ForgotPassword")]
    [AcceptVerbs( "POST")]
    public ForgotPasswordResponse ForgotPassword(string emailId)
    {

        AccountInfo accountInfo = _manager.GetUserByEmailId(emailId);

        if (accountInfo == null)
            return new ForgotPasswordResponse
            {
                Response = "error",
                Message = "Email address not found"
            };

        return new ForgotPasswordResponse
        {
            Response = "success",
            Message = "password reset link set to registered email id"
        };
    }

消费服务电话:

     using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://100.7.11.76");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response12 = client.GetAsync("test.Api/api/account/ForgotPassword?EmailId=" + email + "").Result;
                if (response12.IsSuccessStatusCode)
                {
                    string responseString = response12.Content.ReadAsStringAsync().Result;
                }
            }

3 个答案:

答案 0 :(得分:0)

Route属性更改为[Route("api/account/ForgotPassword")],从POST更改为GET,然后首先从像PostMan这样的REST客户端测试您的方法,然后在您的应用程序中使用它。

答案 1 :(得分:0)

您的WebAPI控制器ForgotPasswordResponse接受动词“POST”,您的WebAPI客户端将其调用为GET。因此,您得到406:方法不允许响应。让控制器接受GET动词或使用PostAsJsonAsync方法而不是GetAsync来调用WebAPI。

答案 2 :(得分:0)

尝试使用身份验证过滤器[AllowAnonymous]

        [AllowAnonymous]
        [Route("ForgotPassword")]
        [AcceptVerbs( "POST")]
        public ForgotPasswordResponse ForgotPassword(string emailId)
        {

            AccountInfo accountInfo = _manager.GetUserByEmailId(emailId);

            if (accountInfo == null)
                return new ForgotPasswordResponse
                {
                    Response = "error",
                    Message = "Email address not found"
                };

            return new ForgotPasswordResponse
            {
                Response = "success",
                Message = "password reset link set to registered email id"
            };
        }