您好:
在Vs2015 內使用[ApiController]
有要去
https://shaurong.blogspot.com/2021/07/aspnet-cs0246-apicontroller-using.html
安裝,但都沒有反應
Microsoft.AspNet.WebApi.Client.5.2.7
Microsoft.AspNet.WebApi.Core.5.2.7
Microsoft.AspNet.WebApi.Core.zh-Hant.5.2.7
請問,ApiController 要手動using 那些?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace API01.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : Controller
{
// GET: WeatherForecast
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild",
"Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
補1:
重建好: 一樣是一堆ERR
VS2023 沒有Core ,只有.net framework
看截圖你的專案是.net framework 4.5.2
.net framwork ApiController的寫法
參考官方的範例是這樣子寫,用繼承的方式 : ApiController
using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
namespace ProductsApp.Controllers
{
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
要 using System.Web.Http;
[ApiController]
寫法是.net core的寫法
想用這種寫法的話,那得把專案類型改成.net core