如何使用内容类型的JSON接受无内容的GET请求?

时间:2019-11-04 14:37:30

标签: c# asp.net-core asp.net-core-2.1

在迁移到ASP.NET Core 2.1之后,我们意识到我们的API的某些使用者正在发送Content-Type标头设置为application/json的GET请求。可悲的是,这些请求过去并没有被拒绝(即使它们应该被拒绝),尽管如此,这仍然是一个巨大的变化。

由于我们的消费者需要彻底解决此问题,这将需要一些时间,因此我们希望暂时接受这些请求,这样我们就不必再等待了。

框架(正确)拒绝了请求,并显示以下错误消息:"A non-empty request body is required."

动作如下:

[Route("api/file/{id:guid}")]
public async Task<IActionResult> Get(Guid id)
{
     // Some simple code here
}

未到达动作内的代码,因为错误在到达动作之前就已经抛出(由于错误的请求)。

@Nkosi的解决方案产生了相同的响应:

[HttpGet("api/file/{id:guid}")]
public async Task<IActionResult> Get([FromRoute]Guid id)
{
     // Some simple code here
}

使用者使用的(PHP)cURL是这样的:

$ch = curl_init(self::API_URL."/file/".$id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-Type: application/json",
    "Application: APPKey ".$this->AppKey,
    "Authorization: APIKey ".$this->ApiKey
));

删除"Content-Type: application/json",行会将请求转换为有效请求,因此我们有99.9%的把握确保此标头的添加是邪恶的。

1 个答案:

答案 0 :(得分:3)

考虑在管道的早期删除中间件中的标头。

class UserLogin {
  constructor(username, password, authLevel) {
    this.username = username;
    this.password = password;
    this.authlevel = authLevel;
  }
}
// Localstorage logins
if (localStorage.getItem(userLogin) == null) {
  var userLogins = [];
  userLogins.push(new UserLogin("Benjamin", 4321, "1"));
  userLogins.push(new UserLogin("Mads", 12345, "1"));
  userLogins.push(new UserLogin("Simon", 1234, "1"));
  userLogins.push(new UserLogin("Jessica", 54321, "1"));
  // Logins for Projectmanagers
  userLogins.push(new UserLogin("Oliver", 1234, "2"));
  userLogins.push(new UserLogin("Sara", 4321, "2"));

  var userLoginstring = JSON.stringify(UserLogin)
  localStorage.setItem("UserLogin", userLoginstring)
} else {
  var employeeList = JSON.parse(localStorage.getItem("UserLogin"))
}

//And my function to validate the user ( Not taking authentication level into account yet, just want it to be able to work)

function validate() {
  // from reg form in HTML
  var uname = document.getElementById("uname");
  var pass = document.getElementById("pass")

  var userLogins = JSON.parse(localStorage.getItem("UserLogin"));
  if (!userLogins) {
    userLogins = [
      //Logins for Employee
      new UserLogin("Benjamin", 4321, "1"),
      new UserLogin("Mads", 12345, "1"),
      new UserLogin("Simon", 1234, "1"),
      new UserLogin("Jessica", 54321, "1"),
      // Logins for Projectmanagers
      new UserLogin("Oliver", 1234, "2"),
      new UserLogin("Sara", 4321, "2"),
    ];
    localStorage.setItem("userLogin", JSON.stringify(userLogins));

    for (let i = 0; i < userLoginsserLogins.length; i++) {
      if (username.value == userLogins && password.value == userLogins) {
        alert("You have been logged in");
        document.location = "Medarbejderside.html";
        return false
      } else {
        alert("Login denied");
      }
    }
  }
}