我不認爲這是可能的了。由於控制器和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";