【问题标题】:C# Azure / Postman - 405 Method not Allowed error on POSTC# Azure / Postman - POST 上出现 405 Method not Allowed 错误
【发布时间】:2017-06-14 09:23:13
【问题描述】:

我按照以下教程设置了我的 azure 后端。

https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter2/custom/

然后我第一次安装了邮递员并设置:

http://apptest.azurewebsites.net/.auth/login/custom

{“用户名”:“阿德里安”,“密码”:“超级机密”}

Json(应用程序/json)

但是,我不断收到此错误:

405 方法不允许

{
  "Message": "The requested resource does not support http method 'GET'."
}

后端代码:

using System;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Claims;
using System.Web.Http;
using Newtonsoft.Json;
using AppTestService.Models;
using AppTestService.DataObjects;

using Microsoft.Azure.Mobile.Server.Login;


namespace AppTestService.Controllers
{
    [Route(".auth/login/custom")]
    public class CustomAuthController : ApiController
    {
        private AppTestContext db;
        private string signingKey, audience, issuer;

        public CustomAuthController()
        {
            db = new AppTestContext();
            signingKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");
            var website = Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME");
            audience = $"https://{website}/";
            issuer = $"https://{website}/";
        }

        [System.Web.Http.HttpPost]
        public IHttpActionResult Post([FromBody] User body)
        {
            if (body == null || body.Username == null || body.Password == null ||
                body.Username.Length == 0 || body.Password.Length == 0)
            {
                return BadRequest();
            }

            if (!IsValidUser(body))
            {
                return Unauthorized();
            }

            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, body.Username)
            };

            JwtSecurityToken token = AppServiceLoginHandler.CreateToken(
                claims, signingKey, audience, issuer, TimeSpan.FromDays(30));
            return Ok(new LoginResult()
            {
                AuthenticationToken = token.RawData,
                User = new LoginResultUser { UserId = body.Username }
            });
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool IsValidUser(User user)
        {
            return db.Users.Count(u => u.Username.Equals(user.Username) && u.Password.Equals(user.Password)) > 0;
        }


    }


    public class LoginResult
    {
        [JsonProperty(PropertyName = "authenticationToken")]
        public string AuthenticationToken { get; set; }

        [JsonProperty(PropertyName = "user")]
        public LoginResultUser User { get; set; }
    }

    public class LoginResultUser
    {
        [JsonProperty(PropertyName = "userId")]
        public string UserId { get; set; }
    }


}

如果我在函数顶部添加 [System.Web.Http.HttpGet],那么我会得到一个不同的错误。 :

415 不支持的媒体类型

{
  "Message": "The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource."
}

这些是标题:

Allow →POST
Content-Length →72
Content-Type →application/json; charset=utf-8
Date →Sat, 28 Jan 2017 22:08:48 GMT
Server →Microsoft-IIS/8.0
X-Powered-By →ASP.NET

【问题讨论】:

  • 您是否在请求中传递了内容类型?
  • 您遇到了两个与 GET 相关的错误。当您使用 Content-Type = "application/json" 发送 POST 请求时,您遇到了什么错误?

标签: c# json azure http-status-code-405


【解决方案1】:

确保在您的请求标头中设置ContentType = "application/json" 在邮递员中,甚至在从任何客户端创建请求时。

将控制器定义更改为

[RoutePrefix("auth/login/custom")]
public class CustomAuthController : ApiController
{
}

只是为了测试,在 POST 上引入一个路由

[System.Web.Http.HttpPost]
[Route("post")]
public IHttpActionResult Post([FromBody] User body)

并尝试向

发出请求

http://apptest.azurewebsites.net/auth/login/custom/post

【讨论】:

  • 这很奇怪!仅出于测试目的,如果您使用的是[Authorize],请尝试在您的 POST 中添加[AllowAnonymous]
【解决方案2】:

您可能确实想从 PostMan 发出 POST 请求,而不是 GET。不要在action上添加[HttpGet],只需在PostMan中将方法设置为POST即可。

并确保在 PostMan 中设置标题 Content-Type: application/json。

【讨论】:

    【解决方案3】:

    在 Azure 服务 api 中确保它使用 [HttpPost]。 如果您能够发送正文参数,则意味着您在调用 API 时选择了 Post in postman,这是正确的。不要更改邮递员电话或 azure api 来获取。这将是不匹配的。

    如果您有权访问 azure 日志,请检查 http Post 是否作为 Get 重定向到 https url,在这种情况下,请尝试直接调用 https。

    在这种情况下,Azure 日志如下所示:

    Received request: POST http://xxx.azurewebsites.net/api/Data/test
    Information Redirecting: https://xxx.azurewebsites.net/api/Data/test
    Received request: GET https://xxx.azurewebsites.net/api/Data/test
    

    在这种情况下,请致电https://xxx.azurewebsites.net/api/Data/test

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多