Original address: https://blog.csdn.net/laymat/article/details/65444701
When we create a web mvc project, we do not support web api interface access, so we need to add additional components to support dual mode.
First of all, we need to prepare three components that web api depends on (currently testing is normal under .net 4/4.5 version, 2.0 has not been tested yet, you need to test it yourself)
1、Microsoft.AspNet.WebApi.Client.5.2.2
2、Microsoft.AspNet.WebApi.Core.5.2.2
3、Microsoft.AspNet.WebApi.WebHost.5.2.2
The web api dependency component download address https://pan.baidu.com/s/1slJHdVJ
After downloading the dependent components, unzip them to the packages directory or other directories. After unzipping, open the editor > Add Reference > Find the downloaded three dependent dlls and reference them (Microsoft.AspNet.WebApi.Client.5.2.2 is System.Net .Http extension package, so there are only two references):
(If you have already referenced System.Web.Http, you need to delete the original reference and re-reference it )
After adding the reference, we need to add a WebApiConfig configuration file in the App_Start directory to initialize the api access route. The code is as follows:
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
- // Web API routing
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
After adding the configuration file, we next need to register the configuration file in the Global.asax global file:
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- GlobalConfiguration.Configure(WebApiConfig.Register);
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- }
(Note: GlobalConfiguration.Configure(WebApiConfig.Register); The registration information must be located before the normal RouteConfig, otherwise it will not take effect.)
After completing the above configuration operations, we have completed the configuration of the basic operating environment of webapi. Next, we will add a web api controller:
- [RoutePrefix("api/Notify")]
- public class NotifyController : ApiController
- {
- [Route("Alipay")]
- public string Alipay()
- {
- return "success";
- }
- }<span style="white-space:pre;"> </span>
[RoutePrefix("api/Notify")] Configure the api access path Example: http://domain/api/Notify
[Route("Alipay")] Example of configuring api access interface : http://domain/api/Notify/Alipay
If you need to set the access mode for a method, you can add [HttpPost] or [HttpGet] above [Route].