簡體   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