【问题标题】:c# asp .net core HTTP POST Request works with Postman but not with my angular client(404 error)c# asp .net core HTTP POST Request 适用于 Postman 但不适用于我的 Angular 客户端(404 错误)
【发布时间】:2019-03-22 12:35:34
【问题描述】:

我的 c# asp .net core Rest Server 有问题。我创建了一个带有测试路由的 AuthenticationController,它似乎正在与 Postman 一起工作,但是当我试图在我的 Angular 6 应用程序中获得相同的结果时,我得到一个 404 错误,表明找不到路由,尽管它是完全相同的 url。

我的 Asp .net 核心控制器:

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class AuthenticationController : ControllerBase
{
    private readonly IAuthenticationService _service;

    public AuthenticationController(IAuthenticationService service)
    {
        _service = service;
    }


    [AllowAnonymous]
    [HttpPost("[action]")]
    public IActionResult Test()
    {
        return Ok("It worked");
    }

}

调用路由的我的 Angular 服务:

import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse, 
HttpHeaders}from'@angular/common/http';


const SERVER_URL = 'http://localhost:4000/api/authentication/';

@Injectable({providedIn: 'root'})
export class LoginService {
public token: string;

constructor(private sessionUser: SessionUserService, private http: 
HttpClient, private rolesService: RolesService) {}



test() {
  return this.http.post(SERVER_URL + 'test', {})
  .map((response: any) => {
    console.log(response);
    return response;
  })
  .catch(err => {
    console.log(err);
    return Observable.of(false);
  });
 }

}

以下是不同的结果:

从我的 Angular 客户端调用路由:

从 Postman 调用路由:

asp .net 核心服务器控制台的输出:

正如您在服务器的控制台日志中看到的,有一个 404 和一个 200 请求已完成。带有 404 的那个是我的申请,带有 200 的那个是 Postman 的。

注意:

CORS 应该不是问题,因为我有 google chrome 扩展程序。

我还尝试使用 angular 支持的代理配置来避免此错误。

【问题讨论】:

  • 您可以先更正链接,例如“this.http”需要链接而不是“this”。
  • 对不起,我的错。只是糟糕的编辑现在修复了它。
  • 您不需要在您的网址中输入localhost:4000
  • “它工作”字符串,但它甚至没有走那么远,因为应用程序没有找到路线。
  • 您通过Postman 发送的Headers 是什么?我看到有 4 个,也许您还需要从 Angular 应用程序发送其中的一些(或全部)...

标签: c# asp.net angular rest http-status-code-404


【解决方案1】:

如您所见,您收到了 404 for OPTIONS 请求。我们在发送跨域请求时发送选项请求。

请确保您在 asp.net 应用程序中的 CORS 已配置。 因为当您使用 POSTMAN 时,它不是跨域请求。

您应该添加响应头 Access-Control-Allow-Origin: *

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 2020-04-23
    • 2020-04-06
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    相关资源
    最近更新 更多