ASP网页API异步操作 - 404错误 [英] Asp Web Api async action - 404 error

查看:215
本文介绍了ASP网页API异步操作 - 404错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种动作的一些API控制器:

I've got some api controller with this action:

public class ProxyController : ApiController {
    public async Task<HttpResponseMessage> PostActionAsync(string confirmKey)
    {
         return await Task<HttpResponseMessage>.Factory.StartNew( () =>
               {
                  var result = GetSomeResult(confirmKey);
                  return Request.CreateResponse(HttpStatusCode.Created, result);
               });
    }
}

这是我的API路由confuguration:

And here is my api routing confuguration:

routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });

当我尝试做任何邮政/ GET请求这个动作,它的回报率404错误。我该如何解决?在此控制器的所有其他未异步操作正常工作。

When I try to make any Post/Get Requests to this action, it's returns '404' error. How can I fix it? All other not-async actions in this controller works fine.

UPD。 JS查询:

UPD. JS query:

$.ajax({
        url: Url + '/api/Proxy/PostActionAsync',
        type: 'POST',
        data: { confirmKey: that.confirmKey },                  
        dataType: 'json',                   
        xhrFields: {  withCredentials: true  },
        success: function (data) {
            ............
        },
        error: function (jqXHR, textStatus, errorThrown) {
             ............
        }                        
});

UPD。加入 [FromBody] 解决我的行动方法的参数,就像在J.斯蒂恩的回答,现在它看起来就像

UPD. Resolved by adding [FromBody] to my parameters in action method just like in J. Steen's answer, now it's look's like

public class ProxyController : ApiController {
       public async Task<HttpResponseMessage> PostActionAsync([FromBody]string confirmKey)
        {
            var someModel = new SomeResultModel(User.Identity.Name);
            await Task.Factory.StartNew(() => someModel.PrepareModel(confirmKey));

            return Request.CreateResponse(HttpStatusCode.OK, someModel);
        }
    }

和它的作品!

推荐答案

对Web API的路由配置的作用有点不同于MVC。

The routing configuration for Web API works a little differently than MVC.

尝试

routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });

请注意缺少 {行动} 作为由网络API的调用时间分辨,自动的,这取决于您使用您请求的HTTP动词。

Note the missing {action} as that is resolved by Web API at call-time, automagically, depending on the HTTP verb you use for your request.

考虑的这篇文章的Web API路由列出(作为一个例子):

Consider this article on Web API routing which lists (as an example):

HTTP Method  URI Path            Action           Parameter
GET          api/products        GetAllProducts   (none)
GET          api/products/4      GetProductById   4
DELETE       api/products/4      DeleteProduct    4

在你的情况,一个动作的异步版本也自动解决。

In your case, the async version of an action is also resolved automatically.

POST         api/products        PostActionAsync  (Post data)

由于我们现在知道控制器名称,请求会是这样:

Since we now know the controller name, requests would be like:

GET api/proxy
GET api/proxy/4
POST api/proxy (with post data)


修改

更多的研究后(简单地说,我承认),我已经找到了问题。

After additional research (brief, I admit) I have found the issue.

您需要添加 [FromBody] 盈您在参数。

You need to add [FromBody] infront of your in-parameter.

public async Task<HttpResponseMessage> PostActionAsync([FromBody] string confirmKey)

这与发送的只是的值(无包装JSON)可以创造奇迹组合。设置内容类型的JSON为应用程序/ x-WWW的形式urlen codeD,而是和发送您的参数作为=+ that.confirmKey

This, combined with sending just the value (no wrapping json) works wonders. Set content type to "application/x-www-form-urlencoded" instead of json, and send your parameter as "=" + that.confirmKey.

替代

如果您不想摆弄内容类型和prefixing = -signs,只是把它作为查询字符串的一部分。忘记 [FromBody] 和休息。呼叫

If you don't want to fiddle around with content-types and prefixing =-signs, just send it as part of the querystring. Forget the [FromBody] and the rest. Call

/api/Proxy/PostActionAsync?confirmKey=' + that.confirmKey

另外,详尽的信息,在这个博客

这篇关于ASP网页API异步操作 - 404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆