2016-03-11 53 views
1

我正在ASP.NET 5 webapi中創建API發佈方法。我有一個要求,我需要創建如下所示的重載Post方法。ASP.NET 5 WebAPI

[HttpPost] 
public bool LogInfo([FromBody]LogEventModel value) 
{ 
} 


[HttpPost] 
public bool LogInfo (String strInformation) 
{ 
} 

我嘗試了多個選項來設置路由參數,如下所示。

[HttpPost("LogInfo/{strInformation}")] 

(或)

[Route("LogInfo/{strInformation}")] 

但它不工作。我希望我在這裏搞點東西。誰能幫忙?

回答

0

我不認爲這是可能的了。由於控制器和Web API控制器現在是相同的事實,因此路由也已統一。你可以閱讀更多關於它here

所以我會做的是,這是我的控制器代碼:

public class HomeController : Controller 
{ 
    // GET: /<controller>/ 
    public IActionResult Index() 
    { 
     ViewBag.Title = [email protected]"{nameof(HomeController)}-{nameof(Index)}"; 
     return View(); 
    } 

    [HttpPost] 
    [Route("home/setsomething2", Name = "SetSomething2")] 
    public void SetSomething([FromBody]SomeValueModel someValue) 
    { 
     var value = someValue; 
    } 


    [HttpPost] 
    [Route("home/setsomething1", Name = "SetSomething1")] 
    public void SetSomething(String someValue) 
    { 
     var value = someValue; 
    } 
} 

public class SomeValueModel 
{ 
    [JsonProperty("somevalue")] 
    public string SomeValue { get; set; } 
} 

而且這是我從視圖Index.cshtml把它稱爲:

function postSomething1() { 
    var url = "@Url.RouteUrl("SetSomething1", new {someValue = "someValue"})"; 
    $.post(url) 
     .done(function() { 
      alert("Succes!"); 
     }) 
     .fail(function (response) { 
      console.log(response); 
      alert("Fail!"); 
     }); 
} 
function postSomething2() { 
    var url = "@Url.RouteUrl("SetSomething2")"; 
    $.ajax({ 
     contentType: 'application/json', 
     data: JSON.stringify({ "somevalue": "myvalue" }), 
     dataType: 'json', 
     success: function() { 
      alert("Succes!"); 
     }, 
     error: function() { 
      alert("Error!"); 
     }, 
     processData: false, 
     type: 'POST', 
     url: url 
    }); 
} 

你可以然而令SetSomething2的路由更REST風格,如:

[Route("home/setsomething/{someValue}", Name = "SetSomething2")] 

注:注意路徑'home/setsomething /'是如何清除數字的,所以這將是我首選的方式。

如果你真的不想製作不同的路線,你不能使用命名路線。所以你必須拋棄像名字:

[Route("home/setsomething")] 

和:

[Route("home/setsomething/{someValue}")] 

然後叫他們的jQuery像例如:

var url = "home/setsomething/somevalue"; 
0

這是我做的。

我更喜歡爲每個控制器指定的路由通過與註解它們:

[Route("[controller]/[action]")] 

然後,一個動作可能看起來像:

[HttpPost] 
[ActionName("GetSomeDataUsingSomeParameters")] 
public List<Thing> GetSomeDataUsingSomeParameters([FromBody] MyParameters parms) 
{ 
    return Repo.GetData(parms); 
} 

該請求可能看起來像:

http://myhost/mycontroller/GetSomeDataUsingSomeParameters 

通過POST方法將參數作爲Json結構傳遞到主體中。例如:

{"Parameter1":1,"Parameter2":"a string"} 

請求中還應註明:

Content-Type: application/json 

所以我們說你的類事情是:

public class Thing 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

則響應可能會(與找到的兩件事數據庫):

[{"Id":1,"Name":"First thing"},{"Id":2,"Name":"Another thing"}]