2017-09-03 55 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那麼一定要配置相應的郵差。