我突然想到了一个我不明白的问题。我尝试创建一个API控制器来做一些事情,但没有任何效果,所以我一步一步地回到了我的控制器与以下教程中的相同:
public class CityController : Controller
{
public CityController()
{
}
[HttpGet("city")]
public JsonResult Get()
{
return new JsonResult(new List<object>()
{
new { id = 1, Name ="asd"},
new { id = 2, Name ="dsa"}
});
}
在我的创业公司:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "City", action = "Index" }
);
}
);
}
它仍然没有通过邮递员向我发回任何东西......我无法理解为什么?!
我做错了什么?
答案 0 :(得分:0)
据我了解,在邮递员中,您需要在标题中设置相应的内容类型,例如:
Content-Type:application/json
该URL将类似于: -
http://xxx:999/City
<强>更新强> 这对我有用。
URL
http://localhost:57909/api/values
控制器
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
public JsonResult Get()
{
return new JsonResult(new List<object>()
{
new { id = 1, Name ="asd"},
new { id = 2, Name ="dsa"}
});
}
}
答案 1 :(得分:0)
[HttpPost] //whichever you prefer, I am fond of HttpPost for a couple of reasons so I'd recommend using that.
public IHttpActionResult City() //add string city or any input class variable if you're taking any inputs
{
return Ok(new List<object>()
{
new { id = 1, Name ="asd"},
new { id = 2, Name ="dsa"}
}); //This will return a JSON serialized result
}
WebApiConfig.cs可能如下所示:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var settings = config.Formatters.JsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
);
}
}
如果您选择HttpPost
,请务必相应地配置邮差。