我试图使用ASP.NET Web API返回一个JSON文件(用于测试).
public string[] Get()
{
string[] text = System.IO.File.ReadAllLines(@"c:\data.json");
return text;
}
Run Code Online (Sandbox Code Playgroud)
在Fiddler中,它确实显示为Json类型,但是当我在Chrome中调试并查看它出现的对象和各行的数组(左)时.正确的图像是我使用它时对象应该是什么样子.
任何人都可以告诉我应该返回什么以正确的格式获得Json结果?
出于某种原因,Request.CreateResponse在VS2012中现在是"红色",当我将鼠标悬停在IDE的使用状态时
无法解析符号'CreateResponse'
这是ApiController类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using GOCApi.Attributes;
using GOCApi.Models;
using GOCApi.Models.Abstract;
using AttributeRouting;
using AttributeRouting.Web.Http;
namespace GOCApi.Controllers
{
[RoutePrefix("Courses")]
public class CoursesController : ApiController
{
private ICoursesRepository _coursesRepository { get; set; }
public CoursesController(ICoursesRepository coursesRepository)
{
_coursesRepository = coursesRepository;
}
[GET("{id}")]
public HttpResponseMessage Get(int id)
{
var course = _coursesRepository.GetSingle(id);
if (course == null)
return Request.CreateResponse(HttpStatusCode.NotFound, "Invalid ID");
return Request.CreateResponse(HttpStatusCode.OK, course);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当然,代码确实可以编译和工作,只是看到屏幕上的所有"红色"真的很烦人.此外,当我输入时,intellisense现在不起作用Request.CreateResponse …
是否可以使用返回值和异常更改此代码:
public Foo Bar(Bar b)
{
if(b.Success)
{
return b;
}
else
{
throw n.Exception;
}
}
Run Code Online (Sandbox Code Playgroud)
对此,它为成功和失败抛出了单独的例外
public Foo Bar(Bar b)
{
throw b.Success ? new BarException(b) : new FooException();
}
try
{
Bar(b)
}
catch(BarException bex)
{
return ex.Bar;
}
catch(FooException fex)
{
Console.WriteLine(fex.Message);
}
Run Code Online (Sandbox Code Playgroud) 如何从WebAPI方法返回HTTP 403?我试过用HttpStatusCode.Forbidden抛出一个HttpResponseException,我试过了
return request.CreateErrorResponse(HttpStatusCode.Forbidden, pEx);
Run Code Online (Sandbox Code Playgroud)
两者都不奏效.两者总是返回HTTP 200.我错过了什么?它必须是简单的东西,但我没有看到它.
我是webapi的新手,并开发了一个小的webapi,它有一些动作并返回我的自定义类,名为Response.
Response班public class Response
{
bool IsSuccess=false;
string Message;
object ResponseData;
public Response(bool status, string message, object data)
{
IsSuccess = status;
Message = message;
ResponseData = data;
}
}
Run Code Online (Sandbox Code Playgroud)
[RoutePrefix("api/customer")]
public class CustomerController : ApiController
{
static readonly ICustomerRepository repository = new CustomerRepository();
[HttpGet, Route("GetAll")]
public Response GetAllCustomers()
{
return new Response(true, "SUCCESS", repository.GetAll());
}
[HttpGet, Route("GetByID/{customerID}")]
public Response GetCustomer(string customerID)
{
Customer customer = repository.Get(customerID);
if (customer == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
} …Run Code Online (Sandbox Code Playgroud)