简体   繁体   English

为什么我在这个Web API请求上获得HTTP 404?

[英]Why do I get an HTTP 404 on this one Web API request?

I am making a POST request, and getting a 404 - Not Found error back, to this controller and action: 我正在发出POST请求,并向此控制器和操作发回404 - Not Found错误:

[AllowAnonymous]
[System.Web.Mvc.RoutePrefix("api/Appt")]
public class AppointmentController : BaseController
{
    [HttpPost]
    [Route("")]
    public AppointmentDto Post(AppointmentDto model)
    {
        Db.Appointments.Add(model);
        Db.SaveChanges();
        Logger.Info($"Appointment ID {model.Id} created.");
        return model;
    }
}

The request is made from a WPF client using HttpClient from the Microsoft.AspNet.WebApi.Client package. 该请求来自使用Microsoft.AspNet.WebApi.Client包中的HttpClient的WPF客户端。 The client is configured like so: 客户端配置如下:

public abstract class BaseRestClient
{
    protected const string BaseAddress = "http://localhost:51009";
    protected HttpClient Client;

    protected virtual void ConfigureClient()
    {
        Client = new HttpClient { BaseAddress = new Uri(BaseAddress) };
        Client.DefaultRequestHeaders.Clear();
        Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }
}

And called as follows: 并呼吁如下:

var response = await Client.PostAsJsonAsync("api/Appt", model, cancellationToken);

Properties on response include: response属性包括:

StatusCode: 404`
ReasonPhrase: 'Not Found'`
RequestMessage: 
    {Method: POST, RequestUri: 'http://localhost:51009/api/Appt'`

This is the only request I'm making to a POST action, with a model parameter, but, ironically, a POST request to a GET action on an almost identical controller works fine. 这是我使用model参数对POST操作进行的唯一请求,但具有讽刺意味的是,对几乎相同的控制器上的GET操作的POST请求工作正常。 With the controller: 使用控制器:

[System.Web.Mvc.RoutePrefix("api/Person")]
public class PersonController : BaseController
{
    [HttpPost]
    public async Task<IEnumerable<PersonDto>> Get()
    {
        Db.Configuration.LazyLoadingEnabled = false;
        return await Db.Persons.ToListAsync();
    }
}

the request made as below works fine and returns all my Person objects: 如下所示的请求工作正常并返回我的所有Person对象:

HttpResponseMessage response = await Client.PostAsync("api/Person", null, cancellationToken);

Two similar requests to GET actions also work perfectly. GET操作的两个类似请求也可以完美地工作。

So why would the one resource be found, and the other not? 那么为什么要找到一个资源,另一个不能找到? Are the any other, hidden reasons a 404 would be returned other than the requested resource not being found? 是否有任何其他隐藏的原因除了找不到所请求的资源之外还会返回404?

Could this be due to a conflict with two types of routing, eg 这可能是由于与两种类型的路由冲突,例如

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

I have to use attribute routing in one place, the comment explains why: 我必须在一个地方使用属性路由,注释解释了原因:

[HttpPost]
[Route("Get")] 
// NOTE HTTP 405 - Method not allowed when this action is named 'Get'.
public async Task<IEnumerable<BranchDto>> Fetch()
{
    Db.Configuration.LazyLoadingEnabled = false;
    return await Db.Branches.ToListAsync();
}

You are using the wrong route prefix attribute. 您使用了错误的路由前缀属性。

System.Web.Mvc.RoutePrefix("api/Appt")

is for MVC not Web API. 适用于MVC而非Web API。

You need the one in System.Web.Http 你需要System.Web.Http那个

System.Web.Http.RoutePrefix("api/Appt")

The reason the person controller example worked is because it defaulted back to convention-based routing. 人员控制器示例工作的原因是因为它违反了基于约定的路由。

original would have worked if you called POST http://localhost:51009/api/Appointment via convention-based routing. 如果您通过基于约定的路由调用POST http://localhost:51009/api/Appointment ,原来会有效。

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

相关问题 当我尝试将获取请求中的日期变量传递给Web api方法时,为什么会出现错误404? - Why get error 404 when I try to pass date variable in get request to web api method? 为什么我会尝试将404大文件发布到Core Web API - Why do I get a 404 trying to post a large file to a Core Web API 为什么http get方法在asp.net Web API中接受HTTP发布请求? - Why does an http get method accepts http post request in asp.net web api? HTTP 获取请求 SQL 服务器 web ZDB974238714CA8DE634A7CE1D083A14 - HTTP Get request SQL server web API 我如何在ASP.NET Web API中记录原始HTTP请求,而不管它是否路由到控制器? - How do I log the raw HTTP request in ASP.NET Web API whether or not it routes to a controller? 如何从 ASP.NET Web API ValueProvider 中的 HTTP POST 请求检索正文值? - How do I retrieve body values from an HTTP POST request in an ASP.NET Web API ValueProvider? 当我使用参数向Web API请求时,为什么会得到“全部获取”而不是“单一获取” - Why I get Get all instead of single when I make a request to a web API with a parameter 获取自定义答案,即 Web API 中 HTTP Post 请求的对象 - Get a custom answer, an object for an HTTP Post request in a Web API 我得到404错误 - asp.net web api - I get 404 error - asp.net web api Web Api中的异步HTTP请求 - Async HTTP Request in Web Api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM