简体   繁体   中英

How to create common method for web api Url in asp.net MVC4

I've started using Web Api. I try to create one master method for all web api request for example in below Snapshot there method name GetMenu() and parameter would be userpkid.

快照 1

Now,I will try to create Common Method for web api. when request Come from web api than they separate method name and parameter than call the whatever method name dynamically and pass parameter. For Example request comes For menu Control than they go in menu control for whatever method name and parameter if request come for country control than go in country control for whatever method name and parameter. so how can i achieve this..

快照 2

The solution depends on whether the parameter name is important. By default within Microsoft Web Api, the query string parameter name must match the parameter variable name of the method . For example:

If the url is

"api/MenuData/GetMenu?UserPKId=1"

then the controller method must have the following parameter list

public MyModel CommonWebApiMethod(string MethodName, string UserPKId)

Unimportant parameter name

Configure the route:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "MethodName",
            routeTemplate: "api/MenuData/{MethodName}",
            defaults: new { controller = "Common", action = "CommonWebApiMethod" }
        );
    }
}

Controller:

public class CommonController : ApiController
{
    [HttpPost]
    public MyModel CommonWebApiMethod(string MethodName, string parameter)
    {
        return new MyModel { MethodName = MethodName, Parameter = parameter };
    }
}

Calling url:

"api/MenuData/GetMenu?parameter=1"

Important parameter name

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "ParameterName",
            routeTemplate: "api/MenuData/{MethodName}/{parameterName}",
            defaults: new { controller = "Common", action = "CommonWebApiMethod" }
            );
    }
}

Controller:

public class CommonController : ApiController
{
    [HttpPost]
    public MyModel CommonWebApiMethod(string MethodName, string parameterName, string parameter)
    {
        return new MyModel { MethodName = MethodName, Parameter = parameter };
    }
}

Calling url:

"api/MenuData/GetMenu/UserPKId?parameter=1"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM