C#/。净邮政请求不断返回控制器中的400个不良请求

发布于 2025-01-22 18:29:56 字数 1472 浏览 2 评论 0原文

我试图写一个简单的api te接收帖子请求。当我尝试测试方法时,它会一直导致邮递员的400个不良要求。我首先认为这个问题是因为JSON机构进行了挑选。因此,请确保我从控制器中删除了该逻辑,但是该请求仍然返回了400个状态代码。

因此,除了方法本身之外,我从方法中删除了所有内容,只返回ok('Hello world');仍然是400。

我现在剩下的是:

  [Route("api/v1/service/")]
  public class ServiceController : Controller
  {

    public ServiceController()
    {

    }

    [HttpGet("get")]
    public IActionResult Get()
    {
      return Ok("GET works fine");
    }

    [HttpPost("post")]
    public IActionResult Post()
    {
      return Ok("Hello World"); // <-- Keeps returning 400
    }

  }

Get方法正常工作,但是当我将空的帖子调用发送到/api/v1/service/post时,我会得到一个不好的请求。

我还注意到,当我将路线更改为不存在的不同事物或随机的事物时,它也会获得400,而不是404

。未定义的还会导致不良请求。

我一直在请求表格中更改小问题,添加/删除ContentType或接受标头并调整我的startup.cs。但是我对.NET进行的每个帖子都会导致400个状态代码。

编辑

此可能与startup.cs中的路由有关:

      app.UseHsts();

      app.UseMvc(routes =>
      {
      });
      app.UseRouting();

这是Post Man中的请求:

GET:

帖子:

样本中的代码是从我的原始API方法中更改的,但是这个想法是相同的。我将示例复制到项目中的一个新文件,并在邮递员中单击“创建新请求”。因此,标题是默认的。

I am trying to write a simple API te receive POST requests with a body. When I try to test my method it keeps resulting in a 400 bad request in Postman. I first thought the issue was with deserializing the JSON body. So to be sure I stripped out that logic from the controller, but the request still returned a 400 status code.

So I removed everything from my method except for the method itself, only returning Ok('Hello World'); and still the response was a 400.

What I have left for now is this:

  [Route("api/v1/service/")]
  public class ServiceController : Controller
  {

    public ServiceController()
    {

    }

    [HttpGet("get")]
    public IActionResult Get()
    {
      return Ok("GET works fine");
    }

    [HttpPost("post")]
    public IActionResult Post()
    {
      return Ok("Hello World"); // <-- Keeps returning 400
    }

  }

The GET method works fine, but when I sent an empty POST call to /api/v1/service/post in Postman I get a bad request.

I also noticed that when I change the route to something different or random that does not exists it also gets a 400, instead of a 404.

So making a POST call to api/v1/service/this-route-is-not-defined also results in a bad request.

I keep changing small things in my request form adding/removing ContentType or Accept headers and adjusting my StartUp.cs . But every POST call I make to .NET seems to result in a 400 status code.

Edit

This might be related to the routing in Startup.cs:

      app.UseHsts();

      app.UseMvc(routes =>
      {
      });
      app.UseRouting();

This is the request in POST man:

GET:
enter image description here

POST:
enter image description here

The code in the sample was offcourse altered from my original API method, but the idea is the same. I copied the sample to a new file in my project and clicked in Postman on create new request. So headers are the default ones.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一抹淡然 2025-01-29 18:29:56

首先,对这个问题的答案和评论都很有用。

我找到了罪魁祸首。显然,在startup.cs文件中启用了一个选项,该文件将对所有可以修改诸如post,put,delete之类的API调用的反式令牌检查。当使用JavaScript fetch()从前端调用API时,这不是问题。令牌被添加到文档中的标签中,您可以将其添加到此类请求标题中:

headers.Append('x-xsrf-token',(document.getElementsByname(“ _____ requestverificationToken”)[0] ).value)

为了使邮递员的发布通话,例如,您可以在操作上方暂时添加此行。

[ignoreantiforgerytoken]

因此,工作示例会这样:

  [Route("api/v1/service/")]
  public class ServiceController : Controller
  {

    public ServiceController()
    {

    }

    [HttpGet("get")]
    public IActionResult Get()
    {
      return Ok("GET works fine");
    }

    [IgnoreAntiforgeryToken]
    [HttpPost("post")]
    public IActionResult Post()
    {
      return Ok("Hello World"); // <-- Keeps returning 400
    }

  }

重要的是考虑何时使用[ignoreantiforgeryToken],而不要使用它。关于Alt Ready希望API密钥的方法,例如,您可以在生产环境中使用它。但是,当方法公开时,反虐待令牌是一种保护您的方法免受攻击者或试图垃圾邮件API的人/机器人的方式。

First of all, the answers and comments given to this question were all helpfull.

I found the culprit. Apperently there was an option enabled in the Startup.cs file that puts an anti-forgery token check on all API calls that can modify stuff, like POST, PUT, DELETE. This is not an issue when calling the API from the frontend with a Javascript fetch() for instance. The token is added to a tag in the document and you can add to the request headers like this:

headers.append('X-XSRF-TOKEN', (document.getElementsByName("__RequestVerificationToken")[0] as any).value)

To be able to make a POST call from Postman for instance you can add this line temporarely above your action.

[IgnoreAntiforgeryToken]

So working example would like this:

  [Route("api/v1/service/")]
  public class ServiceController : Controller
  {

    public ServiceController()
    {

    }

    [HttpGet("get")]
    public IActionResult Get()
    {
      return Ok("GET works fine");
    }

    [IgnoreAntiforgeryToken]
    [HttpPost("post")]
    public IActionResult Post()
    {
      return Ok("Hello World"); // <-- Keeps returning 400
    }

  }

It is important to think about when to use [IgnoreAntiforgeryToken] and not to use it. On methods that allready expect an API key for instance you can use it in a production environment. But when method is public the anti-forgery token is a way of protecting your method from attackers or people/robots trying to spam your API.

轻许诺言 2025-01-29 18:29:56

缺少的mapcontrollers()

您在startup.cs中

app.MapControllers();

添加mapcontrollers(),这是基于属性的路由所必需的。如果您使用的.NET版本为&lt; 6.0然后添加这样的添加:

app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

称为映射属性路由控制器。

Your missing MapControllers()

In your startup.cs add MapControllers(), this is required for attribute based routing.

app.MapControllers();

If the version of .NET you are using is < 6.0 then add like so:

app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

MapControllers is called to map attribute routed controllers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文