在webapi asp.net中我收到以下错误。,响应状态代码不表示成功404(未找到)

时间:2016-06-10 06:38:16

标签: c# asp.net asp.net-web-api

从Web API调用get方法时出现以下错误。 这是我的控制器类。

[RoutePrefix("api/AnnouncementController")]
public class AnnouncementController : ApiController
{
    // GET api/<controller>
    [Route("{code}")]
    [HttpGet]
    public IEnumerable<EAnnouncement> Get(string code)
    {
        return AnnouncementC.getdata(code);
    }
    ...
}

这是我的配置:

{
     public static void Register(HttpConfiguration config)
     {
         // Web API routes
         config.MapHttpAttributeRoutes();
     }
}

public class Global : System.Web.HttpApplication
{    
    protected void Application_Start(object sender, EventArgs e)
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

我在这里调用get方法。但是没有得到错误。请帮帮我

protected void Page_Load(object sender, EventArgs e)
{
    string Jcode = (string)(Session["JCode"]);

    GridView2.DataSource = addressBookGrid_GetData(Jcode);
    GridView2.DataBind();
}

public IQueryable<EAnnouncement> addressBookGrid_GetData(string code)
{
     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri("http://localhost:1146");
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

     HttpResponseMessage response = client.GetAsync("api/AnnouncementController").Result;
     response.EnsureSuccessStatusCode();

     List<EAnnouncement> addressBooks = response.Content.ReadAsAsync<List<EAnnouncement>>().Result;

     return addressBooks.AsQueryable();    
 }

1 个答案:

答案 0 :(得分:1)

在调用服务时删除控制器名称

[RoutePrefix("api/Announcement")]

 HttpResponseMessage response = client.GetAsync("api/Announcement").Result;

你的api方法期望一个参数传递参数,如

 client.GetAsync("api/Announcement/1").Result;

[Route("api/Announcement/{code}")]在您的操作方法

的顶部使用此属性进行装饰