Skip to main content
 首页 » 编程设计

c#之带有 Action 和 id 的 web api 路由

2024年02月05日29duanxz

我刚开始使用 web api,我想在我的 Controller 中调用一个特定的方法。

我有

全局.asax

protected void Application_Start() 
{ 
    GlobalConfiguration.Configure(WebApiConfig.Register); 
} 

具有这些路由的 WebApiConfig 类

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

和我的 Controller

[HttpGet] 
public HttpResponseMessage GetPatSummary(string PatId) 
{ 
   PatientSummary Pat = new PatientSummary(); 
 
   HttpResponseMessage Response = new HttpResponseMessage(); 
   string yourJson = Pat.GetPatient(PatId); 
   Response = this.Request.CreateResponse(HttpStatusCode.OK, yourJson); 
   return Response; 
} 
 
[ActionName("DefaultAction")] //Map Action and you can name your method with any text 
public IHttpActionResult GetPatient(int id) 
{ 
    Object Obj = new object(); 
 
    if (Obj!=null) 
    { 
       return NotFound(); 
    } 
    return Ok(Obj); 
} 

我使用的网址是

http://localhost/mdmwapi/api/MdmwPatientController/GetPatSummary/sgdgdgddhdhd1334254

但是我得到这个错误 路径段不能包含两个连续的参数。它们必须用“/”或文字字符串分隔。

我快疯了:-)

请您参考如下方法:

使用属性路由

[HttpGet] 
[Route("api/MdmwPatientController/GetPatSummary/{PatId}")] 
public HttpResponseMessage GetPatSummary(string PatId) 
{ 
    PatientSummary Pat = new PatientSummary(); 
 
    HttpResponseMessage Response = new HttpResponseMessage(); 
    string yourJson = Pat.GetPatient(PatId); 
    Response = this.Request.CreateResponse(HttpStatusCode.OK, yourJson); 
    return Response; 
} 

然后你可以使用

请求它
http://localhost/api/MdmwPatientController/GetPatSummary/yourpatid 

您也可以通过这种方式使用属性路由映射任何 url