【问题标题】:ASP.NET WebAPI and Angular integration. Collection not foundASP.NET WebAPI 和 Angular 集成。未找到集合
【发布时间】:2020-08-13 08:08:45
【问题描述】:

首先,对不起我的英语。 我正在尝试将 asp.net web api 与 Angular 集成。目前我只实现了 get 方法,当我在 Angular 中调用它时,我总是得到 404 错误。有谁知道如何解决?
WebApiConfig.cs

    public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Servizi e configurazione dell'API Web
        var cors = new EnableCorsAttribute(origins: "*", headers: "*", methods: "*");
        config.EnableCors(cors);

        // Route dell'API Web
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
  
    }
}

Products.cs

    public class Product {
    public string id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public double price { get; set; }
    public int qta { get; set; }

    public List<Product> GetAll() {
        List<Product> productsList = new List<Product>() {
            new Product { id = "id1", name = "prodotto1", description = "descrizione 1", price = 123.42, qta = 4 },
            new Product { id = "id2", name = "prodotto2", description = "descrizione 2", price = 13.42, qta = 4 },
            new Product { id = "id3", name = "prodotto3", description = "descrizione 3", price = 12.45, qta = 2 },
            new Product { id = "id4", name = "prodotto4", description = "descrizione 4", price = 23, qta = 7 },
            new Product { id = "id5", name = "prodotto5", description = "descrizione 5", price = 63.99, qta = 5 }
        };
        return productsList;
    }

    public Product GetProduct(string id) {
        return GetAll().Where(x => x.id == id).FirstOrDefault();
    }
}

ProductController.cs

    [EnableCors(origins: "*", headers: "*", methods: "*")]
public class ProductController : ApiController
{
    [HttpGet]
    public IEnumerable<Product> Get() {
        return new Product().GetAll();
    }
}

WebApiService.ts

@Injectable({


 providedIn: 'root'
})
export class WebapiService {

  constructor(private http: HttpClient) {
  }

  public getValue() {
    return this.http.get<any[]>('http://localhost:44342/api/Product');
  }
}

WebApiTestComponent

  export class WebApiTestComponent implements OnInit {
  value: any[] = [];

  constructor(public webApi: WebapiService) { }

  ngOnInit(): void {
    this.webApi.getValue().subscribe(data => {
      console.log(data);
      this.value = data;
    });
  }

这是错误:

【问题讨论】:

  • 如果我可以提出建议。在最好的情况下,调试 http 动词可能会很棘手。在这个阶段最好避免使用 Angular 并使用 postman 之类的工具来模拟 http 调用。一旦你的 api 按预期工作,然后连接角度调用。
  • 您是否使用 .net Core 作为后端,那么所有的数据序列化问题和响应代码都可以通过继承控制器中的 ControllerBase 并使用 [ApiController] 装饰类来为您处理。然后,您将可以访问 IActionResult 或 ActionResult 作为您的返回对象。
  • @DarrenStreet 我没有使用 .net 核心。它是一个带有 Web API 模板的 ASP.NET Web 应用程序。我尝试使用 Postman,它运行良好。我能够以 JSON 格式获取所有产品。
  • 问题是如果你使用 IActionResult 作为你的返回类型,它会自动序列化你的自定义类。
  • 这是一个很好的入门教程docs.microsoft.com/en-us/aspnet/core/tutorials/…

标签: c# angular typescript asp.net-web-api get


【解决方案1】:

我发现了问题。代码是正确的。问题出在 Angular 项目中。在这个项目中,我在另一个组件中使用了 InMemoryWebApi,这两件事发生了冲突。所以,为了解决这个问题,我在 AppModule 中添加了 passThruUnknownUrl 选项。

InMemoryWebApiModule.forRoot(AppData, {delay: 1000, passThruUnknownUrl: true})

【讨论】:

    【解决方案2】:

    AppData

    @Injectable({
      providedIn: 'root'
    })
    
    export class AppDataService implements InMemoryDbService{
    
      constructor() { }
      createDb(){
    
      }
    }
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    相关资源
    最近更新 更多