The previous time has been committed to the MVC Webapi Technology research, Midway also encountered a lot of obstacles, in particular, API routing settings and URL Access form, so in response to this problem, deliberately made a record for the future of the same confused prawn to learn from:
There is a default API routing config file setting in the App_starta folder in MVC Webapi:
Config. Routes.maphttproute (
Name: "Defaultapi",
Routetemplate: "Api/{controller}/{id}",
defaults:new {id = routeparameter.optional}
);
From this we can see that the API's routing access is not the corresponding action method name, the default access is the name of the corresponding controller. Because the API controller has the corresponding type of naming rules, Get,post, and the corresponding Get,post method with parameters, and so on, the system will be based on the type and parameters of the URL request to determine which action method to use, so when I run the project, The feeling is not very convenient, when to deal with too many methods, and even often encounter the situation is that the request type is the same, and then the parameters are the same situation, so that the system may be chaotic, unable to find the correct action method, can not get the effect we want. To do this, we can modify the corresponding default routing settings, where appropriate, to change the routing to:
Config. Routes.maphttproute (
Name: "Defaultapi",
Routetemplate: "Api/{controller}/{action}/{id}",
defaults:new {id = routeparameter.optional}
);
By adding an action to the default route, you can make it correspond to the corresponding method name.
Then, in the foreground, you can access the corresponding action method in the background via Ajax:
function Handhandler () {
$.ajax ({
Type: ' POST ',
Data:JSON.stringify (document.getElementById ("Handhandler"). Value),
URL: "/api/test/handhandler",
ContentType: "Application/json",
Success:function (Results) {
alert (results);
}
});
}
This is a default with the parameter of the submit post type of access, background data code I will not specifically listed. One of the special emphasis here is that the Get mode access and post way access to a different point, when we execute the URL access with the reference, the background of the corresponding get method of the action function parameter can not need to take [frombody] prefix decoration, And the Post method with the parameter URL needs to add, or you can not find the action you want, the following format:
[HttpPost]
public string Handhandler ([frombody]string requestData)
{
}
This is the overall routing and access process for the MVC Webapi.
Web API Routing Access settings