繁体   English   中英

POST / api / Messaging / 405(不允许使用方法)

[英]POST /api/Messaging/ 405 (Method Not Allowed)

我有一些尝试发布到Web API的方法。 我之前已经做过这项工作,但仍然遇到CORS问题。

我把它放在global.asax中

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

这是API控制器操作签名:

 public void Post([FromBody]Message message)

[FromUri]和[FromBody]都不起作用

我努力了:

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

在WebApiConfig.cs中,同时删除asax文件中的Application_BeginRequest代码,我得到的消息是:405(不允许使用方法)

和控制器:

 public class MessagingController : ApiController
    {
        private IMessagingRepository DataRepository;

        public MessagingController()
        {
            DataRepository = new DataRepositoryFactory().GetMessagingInstance();
        }

        public List<Message> Get([FromUri]MessageGetModel model)
        {
            var result = DataRepository.GetMessages(model.FromId, model.ToId);

            return result;
        }

        public Message Get(string messageId)
        {
            var result = DataRepository.GetMessage(messageId);

            return result;
        }

        public void Post([FromUri]Message message)
        {
            message.Id = ObjectId.GenerateNewId().ToString();
            DataRepository.GetDataRepository().Save(message);

            DataRepository.PostOrUpdateThread(message);

        }
}

1-将[FromUri]更改为[FromBody],因为通常通过消息正文而不是通过查询字符串发布数据,查询字符串通常用于Get请求。

2-从Enable_BeginRequest中删除代码,因为EnableCors就足够了,它将添加Allow标头,然后通过Application_BeginRequest代码再次添加它们,您将在响应中出现相同标头的重复问题。

3-您可以将Route Attribute或RoutePrefix添加到您的方法/控制器中,因此对于您的Post方法,将其替换为如下所示:

[Route("api/Messaging")]
public void Post([FromBody]Message message)
{
    message.Id = ObjectId.GenerateNewId().ToString();
    DataRepository.GetDataRepository().Save(message);

    DataRepository.PostOrUpdateThread(message);
}

4-使用Fiddler邮递员进行测试,并确保您以JSON格式或URL编码将消息添加到请求正文中。

5-如果您将上一点中的消息设置为JSON格式,或者将content-type标头设置为“ application / x-www”,请确保将“ content-type”标头设置为“ application / json” -form-urlencoded”(如果您在上一点中对消息对象进行了编码)。

6-最后,您需要确保您的请求网址已发布到yourapilocatio / api / Messaging网址。

另外,您可以在这里看到我的答案。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM