Web API 2发布404s,但Get工作

问题描述 投票:0回答:1

我很困惑......我有一个非常简单的Web API和控制器,如果我有GET请求,它可以正常工作,但如果我有POST请求则可以使用404。

[RoutePrefix("api/telemetry/trial")]
public class LoginTelemetryController : ApiController
{
    [Route("login")]
    [HttpPost]
    public IHttpActionResult RecordLogin(string appKey) {
        using (var context = new Core.Data.CoreContext()) {
            context.ActivityLogItems.Add(new Domain.Logging.ActivityLogItem()
            {
                ActivityType = "Trial.Login",
                DateUtc = DateTime.UtcNow,
                Key = new Guid(appKey)
            });
            context.SaveChanges();
        }
        return Ok();
    }

当我在邮递员发表反对意见时,我得到:

{
    "message": "No HTTP resource was found that matches the request URI 'http://localhost:47275/api/telemetry/trial/login'.",
    "messageDetail": "No action was found on the controller 'LoginTelemetry' that matches the request."
}

如果我将它更改为[HttpGet]并将appKey作为查询字符串,一切都很好。

我的app启动非常简单:

public void Configuration(IAppBuilder app)
    {
        log4net.Config.XmlConfigurator.Configure();
        HttpConfiguration httpConfig = new HttpConfiguration();
        httpConfig.MapHttpAttributeRoutes(); // <------ HERE

        FilterConfig.RegisterHttpFilters(httpConfig.Filters);
        LoggingConfig.RegisterHandlers(httpConfig.Services);

        ConfigureOAuth(app);
        ConfigureWebApi(httpConfig);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(httpConfig);
    }

谁能发现为什么没有找到POST请求?谢谢

asp.net-web-api2 attributerouting
1个回答
1
投票

如果我取出字符串参数并将其替换为请求对象,它可以工作......

而不是:public IHttpActionResult RecordLogin(string appKey)

我创建了一个请求模型类:

public class PostLoginTelemetryRequest{ 
    public string appKey {get;set;}
}

然后改变签名:

public IHttpActionResult RecordLogin(PostLoginTelemetryRequest request)

一切正常(为什么它不能像MVC5 web dev那样采用常规字符串,我不知道,但无论如何......)

(另请注意,我已经使用字符串方法在客户端的每种格式中尝试过这种方法:form-url-encode,raw body等,所以我很确定它不是调用格式问题)。

© www.soinside.com 2019 - 2024. All rights reserved.