调用web api发布方法错误"远程服务器返回错误:(405)Method Not Allowed"

时间:2014-10-02 01:56:10

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

从MVC控制器调用Web API post方法返回以下错误:

  

"远程服务器返回错误:(405)方法不允许"

在MVC控制器下面Action代码调用一个帮助器类方法,在调试时我可以看到控件从这里移动到下一个方法:

public ActionResult Submit(FormCollection form)
{
    Lead_Options lead = new Lead_Options();            
    lead.Situation = form.GetValue("InsuranceFor").AttemptedValue;
    lead.State = form.GetValue("InsuranceState").AttemptedValue;

    Uri url= Url_Helper.GetUri(BaseUrl, service1+"Post"); // returns http://localhost:52985/api/HealthInsurance/Post

    string obj=  new JavaScriptSerializer().Serialize(lead);

    Object data = WebApi_Helper.PostData(url,obj);

    return RedirectToAction("Parameters");
}

" WebApi_Helper.PostData"是Helper类,一种通用的方法来调用web api:

   public static string PostData(Uri url,string obj)
   {
       string data = null;

       try
       {
           using (WebClient proxy = new WebClient())
           {
               proxy.Headers.Add(HttpRequestHeader.Accept, "application/json");
               data = proxy.UploadString(url,"Post", obj); //Here got error
           }
       }
       catch (Exception ex)
       {               
           throw ex;
       }
       return data;
   }

下面是WebAPI方法代码,但调试请求根本没有来到

[HttpPost]
public void Post(string  lead)
{
    //leadOptService.AddListOptions(lead);
}

请指导我做错了什么以及如何解决。

1 个答案:

答案 0 :(得分:0)

HTTP方法是case sensitive。试试:

data = proxy.UploadString(url,"POST", obj);

data = proxy.UploadString(url, obj); // this overloads POSTs the data

此外,HttpPost属性是多余的,因为按照惯例,Web Api只允许POST public void Post(string lead)

作为一种好的做法,Post应该返回一个值。至少是一个HttpResponseMessage,状态代码为201(表示成功)或500(表示错误)和其他适用的rcodes。