【发布时间】: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 作为你的返回类型,它会自动序列化你的自定义类。
标签: c# angular typescript asp.net-web-api get