繁体   English   中英

在c#后端调用api时角度前端获取错误

[英]Angular front-end getting error when calling api on c# back-end

我有一个Angular前端和ac#webAPI后端。 Angular前端可以从其他URL检索数据(例如http://reqres.in/api/users和json-server --watch db.json)。 c#webAPI成功地将数据返回到api调用(在浏览器中输入并从Postman发送(Get, http:// localhost:49566 / api / people ))。 当前端调用后端时,获取以下内容:HTTP404:NOT FOUND - 服务器未找到与请求的URI(统一资源标识符)匹配的任何内容。 (XHR)选项 - http:// localhost:49566 / people

关于问题是什么,或者它是在前端还是后端的任何建议?

我已经回顾了几个Angular httpclient示例; 但继续体验同样的事情 - 与其他网址合作; 但不是我的c#webAPI的网址。

我试过添加一个帖子选项; 但那并没有解决它。

C#代码:

        public IEnumerable<Person> Get()
        {
            return SQLiteDataAccess.GetPeople();
        }

角度数据服务代码:

  people: object;

  constructor(private http: HttpClient) { }

    searchClick(searchString: string) {
    return console.log('clicked ' + searchString);
  }

  getPeople() {
    const httpOptions = {
      headers: new HttpHeaders({
          'Access-Control-Allow-Origin': 'http://localhost:4200/',
          'Access-Control-Allow-Methods': 'GET',
          'Access-Control-Allow-Headers': '*',
          'Content-Type': 'application/json',
          'Accept': 'application/json'
      })
    };
    return this.http.get('http://localhost:49566/api/People', httpOptions )  
}
}

我需要的是前端成功从后端检索数据; 所以我可以显示它。

更改

   return this.http.get('http://localhost:49566/api/People', httpOptions )

   return this.http.get('http://localhost:49566/api/people', httpOptions )

URL区分大小写。

祝好运!

该问题与服务器端的CORS(服务器端)和方法签名有关。

首先,在API代码(C#)中启用CORS。 请在MSDN中搜索所需的适当命名空间/ dll(例如System.Web.Cors )。

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.EnableCors();

在API控制器派生类(例如)中,请执行此操作以确保允许CORS。 *表示允许所有网址。 根据您的客户(Angular app uri)需求进行更改。

/// <summary>
    /// Provides API for Order entity.
    /// </summary>
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class OrderController : ApiController
    {

在CORS中,发送带有OPTIONS方法的飞行前请求,以便服务器可以响应是否可以使用这些参数发送请求。 它在发送GETPOST之前发送。

回到API代码,在web.config ,请确保您拥有以下内容:

<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

<remove name="OPTIONSVerbHandler" />确保IIS不拦截OPTIONS请求。

同样在web.config ,执行以下操作。 这确保了允许GETPOSTOPTIONS方法。

<httpProtocol>
      <customHeaders>            
        <!--...omitted for brevity-->

        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
      </customHeaders>

最后:

[HttpGet]
public IEnumerable<Person> Get()
        {
            return SQLiteDataAccess.GetPeople();
        }

在Angular的客户端代码中没有必要对CORS做任何事情。 希望有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM