Tag: asp.net web api

Asp.net Web API返回非描述性错误500

在我的设置中,如果Web API请求发生任何错误,我将收到错误500。 例如这个简单的代码。 public IQueryable<Article> Get(){ throw new Exception("error"); return db.Articles; //yeah i know.. unreachable, not the point } 我期望的(以及常规的MVC控制器中会发生什么): 我得到(在Web API中): 我的网页configuration: <customErrors mode="Off"/> <compilation debug="true" targetFramework="4.5"> //under webserver <httpErrors errorMode="detailed"/> 应用程序池在集成模式下运行4.0。 启用32位应用程序。 我怎样才能得到在浏览器中出现的错误? 或者至less在debugging过程中?

Async WebApi Thread.CurrentCulture

我有一个自我托pipe的OWIN托pipe的Web API项目,为我提供了一些基本的REST方法。 我想要多语言的错误消息,所以我使用资源文件和一个BaseController将Thread.CurrentCulture和Thread.CurrentUICulture设置为请求的Accept-Language标头。 public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) { if (controllerContext.Request.Headers.AcceptLanguage != null && controllerContext.Request.Headers.AcceptLanguage.Count > 0) { string language = controllerContext.Request.Headers.AcceptLanguage.First().Value; var culture = CultureInfo.CreateSpecificCulture(language); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; } base.ExecuteAsync(controllerContext, cancellationToken); } 这一切都很好,但问题出现,如果我使我的控制器方法asynchronous 。 当我在方法中使用await时,它可能会在另一个线程中继续,所以CurrentCulture和CurrentUICulture将会丢失。 这是我用来find这个问题的一个小例子。 public async Task<HttpResponseMessage> PostData(MyData data) { Thread currentThread = Thread.CurrentThread; await SomeThing(); if […]

为什么Thread.CurrentPrincipal需要“等待Task.Yield()”?

下面的代码被添加到新创build的Visual Studio 2012 .NET 4.5 WebAPI项目中。 我试图在asynchronous方法中分配HttpContext.Current.User和Thread.CurrentPrincipal 。 Thread.CurrentPrincipal的分配不正确,除非await Task.Yield(); (或其他任何asynchronous)被执行(传递true到AuthenticateAsync()将导致成功)。 这是为什么? using System.Security.Principal; using System.Threading.Tasks; using System.Web.Http; namespace ExampleWebApi.Controllers { public class ValuesController : ApiController { public async Task GetAsync() { await AuthenticateAsync(false); if (!(User is MyPrincipal)) { throw new System.Exception("User is incorrect type."); } } private static async Task AuthenticateAsync(bool yield) { if […]

HttpClient与HttpWebRequest

我有一个大文件,我必须发送到一个web api客户端…数据是多部分。 问题是,如果文件是通过http web请求发送的,那么它会在webapi上快速上传。 对于这个请求,文件内容直接写在请求stream上。 就像通过Httpclient(.net 4.5)发送相同的文件一样,与http web请求相比,上传速度很慢。 我在Httpclient post async中使用multipartformdatacontent。 那么,对于大文件,我们是否只能使用Web请求? 还是有任何设置上的Httpclient,使上传更快?

DataAnnotation为必需属性

首先它有效,但今天它失败了! 这是我如何定义date属性: [Display(Name = "Date")] [Required(ErrorMessage = "Date of Submission is required.")] [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)] [DataType(DataType.Date)] public DateTime TripDate { get; set; } 它一直在工作。 但今天,当我调用相同的ApiController行动: [HttpPost] public HttpResponseMessage SaveNewReport(TripLeaderReportInputModel model) Firebug报道: ExceptionMessage: "Property 'TripDate' on type 'Whitewater.ViewModels.Report.TripLeaderReportInputModel' is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be […]

自定义JsonConverter(Web API)中的Json.Net JsonSerializer中的自引用循环

该项目是一个Asp.Net Web API Web服务。 我有一个types层次结构,我需要能够序列化到和从Json,所以我从这个SO的代码: 如何在JSON.NET中实现自定义JsonConverter反序列化基类对象的列表? ,并将转换器应用于我的层次结构的基类; 像这样的东西(这里有伪代码隐藏不相干的东西): [JsonConverter(typeof(TheConverter))] public class BaseType{ ///note the base of this type here is from the linked SO above private class TheConverter : JsonCreationConverter<BaseType>{ protected override BaseType Create(Type objectType, JObject jObject){ Type actualType = GetTypeFromjObject(jObject); /*method elided*/ return (BaseType)Activator.CreateInstance(actualType); } } } public class RootType { public BaseType BaseTypeMember […]

如何使用IHttpActionResult设置自定义标题?

在ASP.NET Web API 2中, IHttpActionResult在简化控制器代码IHttpActionResult提供了很大的价值,我不愿意停止使用它,但是我遇到了一个问题。 我需要设置一个传出的响应ETag,我找不到任何属性,让我访问响应的标题。 目前我使用ApiController的Ok<T>(T content)辅助方法,该方法返回一个OkNegotiatedContentResult<T>对象。 这似乎没有任何暴露,这将让我修改标题。 我是否缺less某些东西,或者在使用库存IHttpActionResulttypes时真的没有办法做到这一点? 我考虑过一个消息处理程序,但是接下来我必须弄清楚如何将ETag传递出去(对于不同的动作,ETag的生成方式是不同的,所以不需要为所有的操作制作通用的处理程序)。 我想避免使用原始的HttpResponseMessage,但目前看起来很困难。

从WebAPI 2端点返回自定义HTTP状态码

我正在WebAPI 2中的一个服务,端点当前返回一个IHttpActionResult 。 我想返回一个状态码422 ,但由于它不在HttpStatusCode枚举中,所以我不知道如何发送它,因为所有的构造函数都需要一个参数HttpStatusCode 就目前而言,我正在返回BadResult(message) ,但是返回422 +消息对我的客户来说更具描述性和实用性。 有任何想法吗?

POSTstring到ASP.NET Web Api应用程序 – 返回null

我试图从客户端传递一个string到ASP.NET MVC4应用程序。 但是我不能接收string,要么是null,要么post方法找不到(404错误) 客户端代码传输string(控制台应用程序): HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:49032/api/test"); request.Credentials = new NetworkCredential("user", "pw"); request.Method = "POST"; string postData = "Short test…"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse response = request.GetResponse(); Console.WriteLine(((HttpWebResponse)response).StatusDescription); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = […]

WebAPI中的DependencyResolver.SetResolver和HttpConfiguration.DependencyResolver之间有什么区别

我有现有的项目,它使用AutoFac作为IoC。 在注册码我有这些行: var resolver = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(resolver)); config.DependencyResolver = new AutofacWebApiDependencyResolver(resolver); 所以我的问题是什么DependencyResolver.SetResolver和HttpConfiguration.DependecyResolver之间的区别? 我为什么要分配他们?