[英]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: 从MVC控制器调用Web API后方法返回以下错误:
"The remote server returned an error: (405) Method Not Allowed"
“远程服务器返回错误:(405)不允许使用方法”
Below MVC controller Action code calls a helper class method and while debugging I can see control moves from here to next method: 在MVC控制器下面,操作代码调用了一个帮助器类方法,在调试时,我可以看到控件从此处移至下一个方法:
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: “ 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;
}
Below is WebAPI Method code but while debugging request do not come here at all 以下是WebAPI方法代码,但是在进行调试请求时根本没有出现
[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 . HTTP方法区分大小写 。 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)
. 另外,由于Web Api,
HttpPost
属性是多余的,按照惯例,仅允许对public void Post(string lead)
进行POST
。
And as a good practice, the Post
should return a value. 作为一种好的做法,
Post
应返回一个值。 At the very very minimum, an HttpResponseMessage
with status code 201 (for success) or 500 (for errors) and othe rcodes as applicable. 至少,一个
HttpResponseMessage
的状态码为201(表示成功)或500(表示错误)和其他适用的rcode。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.