2017-09-03 56 views
0

我对我不明白的问题感到头痛。我试图创建一个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

我知道你做/城市/获取你的路径?在你的启动中,你将操作定义为索引但索引不存在于你的控制器中?也许Get应该是索引呢? – Adriani6

+0

但是'HttpGet'中的路径不覆盖默认路径吗? @阿德里安尼6,不过,我会试试看。 – sagi

+0

我不完全确定,因为我从来没有使用它的参数,如果我是你我也会从HttpGet中删除参数,并保持空白。 – Adriani6

回答

0

这是我的理解是在邮递员,你将需要设置适当的内容类型在你的头,比如:

Content-Type:application/json 

的网址将随后是这样的: -

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"} 
     }); 
    } 
} 
+0

我该怎么做在邮递员? (顺便说一句,我用Postman在两周前返回json文件,一切正常) – sagi

+0

在postman内的请求中,选择标题链接,在屏幕右侧单击批量编辑链接并粘贴Content-Type:application/json –

+0

不能:/仍然得到'无法得到任何回应' – sagi

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那么一定要配置相应的邮差。