我有一個Web Api控制器。它表現得很奇怪。當我使用PostMan時,我可以訪問Web Api上的POST方法,但是當我使用.net中的HttpWebRequest時,它返回(405)方法不允許。 我在這裏把網頁API代碼:ASP.NET WebApi:(405)方法不允許
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace MyProject.Controllers
{
public class TestController : ApiController
{
[HttpPost]
public int buy(OrderResult value)
{
try
{
if (value.InvoiceDate != null && value.Result == 1)
{
return 0;
}
}
catch{}
return -1;
}
}
public class OrderResult
{
public int Result { get; set; }
public long InvoiceNumber { get; set; }
public string InvoiceDate { get; set; }
public long TimeStamp { get; set; }
}
}
這裏是我的WebApiConfig.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace MyProject
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);
}
}
}
這是我送從另一個.NET項目POST請求:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace MyProject.Controllers
{
public static class WebReq
{
public static string PostRequest(string Url, string postParameters)
{
try
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(Url);
myReq.Method = "POST";
myReq.Timeout = 30000;
myReq.Proxy = null;
byte[] postData = Encoding.UTF8.GetBytes(postParameters);
myReq.ContentLength = postData.Length;
myReq.ContentType = "application/x-www-form-urlencoded";
using (Stream requestWrite = myReq.GetRequestStream())
{
requestWrite.Write(postData, 0, postData.Length);
requestWrite.Close();
using (HttpWebResponse webResponse = (HttpWebResponse)myReq.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
using (Stream str = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(str))
{
return sr.ReadToEnd();
}
}
}
return null;
}
}
}
catch (Exception e)
{
var message = e.Message;
return null;
}
}
}
}
我已經在我的web.config中添加了以下代碼:
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
這很奇怪,因爲我可以從PostMan成功發送POST請求。 PostMan將此代碼發送給API。
POST /api/Test/buy HTTP/1.1
Host: domain.com
Cache-Control: no-cache
Postman-Token: 9220a4e6-e707-5c5f-ea61-55171a5dd95f
Content-Type: application/x-www-form-urlencoded
InvoiceDate=28012016&Result=1
我會很感激任何解決問題的建議。
這不是一個CORS問題,這實際上是我的第一個想法,但OP是純粹從服務器/應用程序而不是瀏覽器+ Ajax運行。 –
Aaa是的,你是對的..對不起:D – hellwd