CSharp - 发现与请求匹配的C# MVC4 WebAPI多操作

  显示原文与译文双语对照的内容
62 1

我搜索了一段时间,但我没有找到的帮助能解决我的问题。我有一个 MVC4 WebAPI项目,我得到了"找到与请求匹配的多个操作。"问题。

这是我的控制器:

public class DataEntryController : ApiController
{
 [HttpPost]
 [ActionName("GetMessageId")]
 public HttpResponseMessage GetMessageId(HttpRequestMessage request)
 {
 }
 [HttpPost]
 [ActionName("RequestXmlDataEntry")]
 public HttpResponseMessage RequestXmlDataEntry(HttpRequestMessage request)
 {
 }
 [HttpPost]
 [ActionName("SendConfirmationXmlDataEntry")]
 public HttpResponseMessage SendConfirmationXmlDataEntry(HttpRequestMessage request)
 {
 }
 [HttpPost]
 [ActionName("SendEvent")]
 public HttpResponseMessage SendEvent(HttpRequestMessage request)
 {
 }
}

这是我的路线:

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
 config.Routes.MapHttpRoute(
 name:"DefaultApi",
 routeTemplate:"api/{controller}/{id}",
 defaults: new { id = RouteParameter.Optional }
 );
 config.Routes.MapHttpRoute(
 name:"API Default 2",
 routeTemplate:"api/{controller}/{action}");
 config.Routes.MapHttpRoute(
 name:"API Default",
 routeTemplate:"api/{controller}/{action}/{id}",
 defaults: new { id = RouteParameter.Optional });
 }
}

以下是我的请求的外观:

public static string PostRequestToRestMethod(string url, string data, IWebProxy proxy, int timeout)
 {
 byte[] byteArray = Encoding.UTF8.GetBytes(data);
 string responseFromServer = string.Empty;
 HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
 webrequest.Method ="POST";
 webrequest.ContentType ="text/xml";
 webrequest.ContentLength = byteArray.Length;
 webrequest.Timeout = timeout;
 if (proxy!= null)
 webrequest.Proxy = proxy;
 var dataStream = webrequest.GetRequestStream();
 dataStream.Write(byteArray, 0, byteArray.Length);
 dataStream.Close();
 HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
 using (StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), Encoding.UTF8))
 {
 responseFromServer = responseStream.ReadToEnd();
 }
 webresponse.Close();
 return responseFromServer;
 }

我正在使用. NET 框架 4.0,所以 WebAPI 2对于我来说是不可能的。任何 toughts?

时间:原作者:0个回答

64 2

你不需要创建不同的routs 。你的所有三个路由都可以通过这个路由来处理。

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 { 
 config.Routes.MapHttpRoute(
 name:"API Default",
 routeTemplate:"api/{controller}/{action}/{id}",
 defaults: new { id = RouteParameter.Optional });
 }
}
原作者:
...