我在其中一个标有System.Web.Http.Authorize
的网络API控制器上遇到了一个奇怪的问题。我在此API上有两种方法(一种GET
和另一种POST
)
[HttpGet]
[Route("highestbid/{auctionId}")]
public IHttpActionResult GetHighestBid(string auctionId)
发布一个是
[Route("placeauctionbid")]
[HttpPost]
public IHttpActionResult PlaceAuctionBid([FromBody]BidViewModel bid)
我的api控制器定义为
[RoutePrefix("api/liveauction")]
[System.Web.Http.Authorize]
public class LiveAuctionController : BaseApiController
现在我的用户已获得授权,当我使用HttpGET
呼叫我的/api/liveauction/highestbid/1a6a46be
时,它会被调用,我在User.Identity.GetUserId()
中有一个值,但是当我调用HttpPOST
端点api时使用HttpWebRequest
会抛出异常
远程服务器返回错误:(404)Not Found。
当我深入了解WebException响应时,我看到了
IIS 10.0详细错误 - 404.15 - 未找到 在Web服务器上配置请求筛选以拒绝请求,因为查询字符串太长。
我在请求正文中发布数据。 现在,如果我在POST函数上添加[AllowAnonymous]
,则使用相同的实现方式将其称为并使用正确的数据。用户在两种情况下都登录,可能导致此行为的原因是什么?
编辑:添加请求函数(我为get / post请求写了这个通用请求管理器函数)
public static ResponseMessage<T> ExecuteRequest<T>(string url, RequestMethod method, string body = null) where T : class
{
ResponseMessage<T> reponse = new ResponseMessage<T>();
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = method.ToString();
httpWebRequest.Accept = "application/json";
if (method == RequestMethod.Post && !string.IsNullOrEmpty(body))
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(body);
streamWriter.Flush();
streamWriter.Close();
}
}
try
{
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
reponse.HttpStatusCode = httpResponse.StatusCode;
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
var responseStream = httpResponse.GetResponseStream();
if (responseStream != null)
{
using (var streamReader = new StreamReader(responseStream))
{
string json = streamReader.ReadToEnd();
reponse.Data = Utility.DeserializeObject<T>(json);
}
}
}
}
catch (WebException webException)
{
reponse.Exception = webException;
reponse.ExceptionStatus = webException.Status;
}
return reponse;
}
我称之为:
ResponseMessage<BidViewModel> apiResponse = RequestManager.ExecuteRequest<BidViewModel>(url, RequestMethod.Post, Utility.SerializeObject(bid));