如何定义WebApi路由以访问方法

时间:2015-04-27 06:38:00

标签: c# .net asp.net-web-api

我想要访问除“GET”,“PUSH”,“PATCH”以外的方法,....

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "Employee",
            routeTemplate: "api/employee/{employeeid}",
            defaults: new { controller = "employee", employeeid = RouteParameter.Optional }
        );

        //for test : not work
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { action = "get", id = RouteParameter.Optional }
        );

        //JSON Formatting
        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling =  Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

我可以访问员工控制器:

    [RoutePrefix("api/employee")]
    public class EmployeeController : ApiController
    {
        public HttpResponseMessage Get() { }
        public HttpResponseMessage Get(int employeeid) {}
        public HttpResponseMessage Post([FromBody] EmployeeModel model){}

        [HttpPut]
        [HttpPatch]
        public HttpResponseMessage Patch([FromBody] EmployeeModel model){}

        [Route("initialisation")]
        public HttpResponseMessage Initialisation() {}
    }

我可以毫无问题地访问:

http://localhost/employee
http://localhost/employee/1

我想访问“初始化”方法:

http://localhost/employee/initialisation

我添加了路由“DefaultApi”,但是当我尝试时出现此错误:

{
  "$id": "1",
  "message": "The request is invalid.",
  "messageDetail": "The parameters dictionary contains a null entry for parameter 'employeeid' of non-nullable type 'System.Int32' 
  for method 'System.Net.Http.HttpResponseMessage Get(Int32)' in 'Pme.WebApi.Controllers.EmployeeController'. 
  An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}

谢谢,

3 个答案:

答案 0 :(得分:0)

我认为这应该成功。您可以尝试像这样修改private StringBuffer request(String urlString) { // TODO Auto-generated method stub StringBuffer chaine = new StringBuffer(""); try{ URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestProperty("User-Agent", ""); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.connect(); InputStream inputStream = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; while ((line = rd.readLine()) != null) { chaine.append(line); } } catch (IOException e) { // Writing exception to log e.printStackTrace(); } return chaine; }

WebApiConfig

通过这种方式,您可以将它们保持打开状态,控制器名称和操作名称是动态的,并尝试按照此格式生成的URL。

更新:

评论“员工”路线代码。只需保持“DefaultApi”路由处于活动状态即可。现在尝试点击此网址:

config.Routes.MapHttpRoute( name: "DefaultApi", //routeTemplate: "api/{controller}/{id}", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );

您显然需要保留主机名和您的参数。

希望这有帮助。

答案 1 :(得分:0)

尝试以下方法:

更改

config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { action = "get", id = RouteParameter.Optional }
    );

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{employeeid}",
            defaults: new { action = "get", employeeid= RouteParameter.Optional }
        );

唯一更改来自" id"的最后一个ID参数的名称到" employeeid"

答案 2 :(得分:0)

您需要在WebApiConfig中注册属性路由

config.MapHttpAttributeRoutes();

请参阅Attribute Routing in ASP.NET Web API 2

或者,您可以准确指定路线的位置

config.Routes.MapHttpRoute("Initialisation", "api/employee/initialisation",
                new {controller = "employee", action = "initialisation"});