简体   繁体   中英

calling web api Post method error “The remote server returned an error: (405) Method Not Allowed”

From MVC controller calling Web API post method returns the below error:

"The remote server returned an error: (405) Method Not Allowed"

Below MVC controller Action code calls a helper class method and while debugging I can see control moves from here to next method:

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" is Helper class, a generic method to be sued to call 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;
   }

Below is WebAPI Method code but while debugging request do not come here at all

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

Please direct me what wrong I m doing and how it can be resolved.

HTTP methods are case sensitive . Try with:

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

or

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

Also, the HttpPost attribute is redundant since Web Api, by convention will only allow POST for public void Post(string lead) .

And as a good practice, the Post should return a value. At the very very minimum, an HttpResponseMessage with status code 201 (for success) or 500 (for errors) and othe rcodes as applicable.

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