Tag: asp.net web api

需要validationdatacontract和datamember

我正在使用web api构建一个API,当收到发布的值并将它们绑定到我的模型时,我得到的错误似乎不合适。 我有一个简单的模型如下: public class Client { [ScaffoldColumn(false)] [JsonIgnore] public int ClientID { get; set; } [Required, StringLength(75)] public string Name { get; set; } [Required] public bool Active { get; set; } } 将此模型发送到我的控制器上的post方法时 public object Post([FromBody]Client postedClient) 它通过x-www-form-urlencoded格式化程序,但它抛出: Property ‘Active’ on type ‘CreditSearch.Api.Models.Rest.Client’ is invalid. Value-typed properties marked as [Required] must also be […]

客户端已断开连接

我在WebAPI的日志中收到以下错误 System.Web.HttpException(0x800703E3):客户端已断开连接。 在System.Web.Hosting.IIS7WorkerRequest.EndRead(IAsyncResult asyncResult)处于System.Threading.Tasks.TaskFactory的System.Web.HttpBufferlessInputStream.EndRead(IAsyncResult asyncResult)1.FromAsyncTrimPromise 1.Complete(TInstance thisRef,Func 3 endMethod,IAsyncResult asyncResult) ,Boolean requiresSynchronization)—抛出exception的前一个位置的堆栈跟踪结束—在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)处System.IO.StreamReader.d__97.MoveNext()—抛出exception的前一个位置的堆栈跟踪结束—在System.Runtime.CompilerServices.TaskAwaiter的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)处System.IO.StreamReader.d__62.MoveNext()中的.HandleNonSuccessAndDebuggerNotification(任务任务)—从抛出exception的上一个位置开始的堆栈跟踪结束—在System.Runtime 位于Microsoft.Owin.OwinRequest.d__0.MoveNext()的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)的.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)—抛出exception的上一个位置的堆栈跟踪结束—在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)处于System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务),位于Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.d__22.MoveNext()—从抛出exception的先前位置开始的堆栈跟踪结束—在Microsoft.Owin.Security.OAuth的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)处.OAuthAuthorizationServerHandler.d__0.MoveNext()—抛出exception的前一个位置的堆栈跟踪结束—在System.Runtime.CompilerServices.TaskAwaiter.Throw Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware 1.d__0.MoveNext()中的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中的ForSuonSuccess(任务任务)—从抛出exception的上一个位置开始的堆栈跟踪结束—在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)处于System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务),位于D:\ UAT中的Web.API.Middleware.OwinMiddleware.d__1.MoveNext() \ Web.API \ Middleware \ OwinMiddleware.cs:第49行 如何通过exceptionfilter处理和忽略这些exception? 为什么会出现此错误,如何重现? 我想捕获并忽略The client disconnected但不是所有HttpException 我看到了类似的问题,但我怎么能在exceptionfilter中做到这一点?

如何处理WebApi错误404

我正在同一个域中使用WebApi2实现MVC 5应用程序。 我现在的问题是如何处理WebApi中的错误404。 我在WebApi中使用路由。 [RoutePrefix(“myapi”)] public class MyApiController : ApiController { [Route(“value”)] public string myvalue() { return “value”; } } 现在我有我的URL “/myapi/value”返回值字符串。 问题是我请求”/myapi/value/bla/bla”或任何不在我的API中的URL,它返回错误404。 我试过这个链接http://weblogs.asp.net/imranbaloch/handling-http-404-error-in-asp-net-web-api ,它只适用于WebApi项目,但不适用于MVC + WebApi项目。 请帮忙。 TIA 更新: 请仔细阅读!!!! 如果您未在WebApi中处理404,这将是默认页面。 它包括你的物理路径。

动态忽略控制器上的WebAPI方法以获取api资源管理器文档

我们实现了一个webAPI,我们有许多API控制器。 我们为API提供API文档,我们要做的是从文档中排除某些Web方法,但我们希望根据我们运行的环境动态完成。 只是为了让你了解我的意思,让我说我有以下网络方法 [ApiExplorerSettings(IgnoreApi = true)] public Product getProduct() { … } 通过将ApiExplorerSettingAttribute上的IgnoreAPI属性设置为true,它会从文档中排除Web方法,这是我们想要的,但我们需要一种动态设置“true”值的方法。 理想情况下,我们希望为每个webMethod创建一个包含bool值的数据库表,并根据这些值设置IgnoreAPi属性的值。 有没有办法实现这个目标? 非常感谢您的帮助。

如何使用FromQuery Attribute获取一个复杂的对象?

如何使用FromQueryAttribute获取复杂对象? [HttpGet] public IActionResult Get([FromQuery] DataGridRequest request) { … } DataGridRequest类如下: public class DataGridRequest { public DataGridPager Pager { get; set; } … } public class DataGridPager { public int Size { get; set; } public int Index { get; set; } } 怎么写uri?

属性路由和CreatedAtRoute

我正在尝试将我的Web Api项目转换为使用属性路由。 我不理解的一件事是POST请求的CreatedAtRoute方法。 在我的WebApiConfig.cs中,我曾经有过 config.Routes.MapHttpRoute( name: “DefaultApi”, routeTemplate: “api/account/{accountId}/site/{siteId}/visitor/{visitorId}/session/{sessionId}/{controller}/{action}”, defaults: new { action = RouteParameter.Optional } ); 我评论了这一点,认为不再需要它,但CreatedAtRoute想要路线的名称而无法找到它。 那么如何处理属性路由呢?

多个可选的查询字符串参数REST API GET

我正在使用web api 2来实现一个宁静的服务。 在对最佳实践进行一些研究之后,每个人似乎都对如何做以下事情有不同的看法。 我有一个GET public HttpResponseMessage Get(string crewId, string shiftDate, int offset = 1, int limit = 10) 此GET方法返回一个列表。 有多种方法可以从此方法获取数据。 仅限crewId 仅限shiftDate 要么 通过crewId和shiftDate获取 你(1)将crewId和shiftDate标记为可选吗? public HttpResponseMessage Get(string crewId = null, string shiftDate = null, int offset = 1, int limit = 10) 然后有一堆if语句来检查填充的内容和未填充的内容以便能够执行操作 if(crewId != null && shiftDate == null){ // Get by […]

HttpRequestMessage.GetClientCertificate()在Web API中返回null

我有一个.NET4.5 WebAPI 2应用程序,它使用SSL客户端证书进行一些自定义安全相关检查。 调试应用程序时,无论我到目前为止尝试了什么, request.GetClientCertificate()都会为任何服务调用返回null 。 经测试的代码: 基本上,在我的服务方面,我有一个类似这样的方法: class CertificateChecker : ICertificateChecker { public bool Check(HttpRequestMessage request) { var cert = request.GetClientCertificate(); } } 我的单元使用request.Properties.Add(HttpPropertyKeys.ClientCertificateKey, cert)传递附加到请求的客户端证书进行测试(证书完全符合预期,validation工作,等等)。 但是,当我使用HttpClient调用实际WebAPI应用程序的测试时,在服务端的request.GetClientCertificate()行设置断点,同一行返回null。 这是我尝试过的: 客户证书: 创建了假CA并将其放入可信CA存储(尝试使用LocalMachine和当前用户)。 创建由该假CA签名的客户端身份validation(1.3.6.1.5.5.7.3.2)证书,并将其放入个人存储(LocalMachine和当前用户)。 (基本上,按照https://www.piotrwalat.net/client-certificate-authentication-in-asp-net-web-api-and-windows-store-apps/和类似的博客) 在我使用HttpClient调用服务的测试中,以下列方式附加了客户端证书(没有一个工作): 使用WebRequestHandler ,将ClientCertificateOptions设置为Manual,并将cert添加到ClientCertificates集合中。 using (var handler = new WebRequestHandler()) { var cert = GetTestCert(); handler.ClientCertificateOptions = ClientCertificateOption.Manual; handler.ClientCertificates.Add(cert); // and so on… } […]

如何从HttpResponseMessage检索传递的exception(HttpStatusCode,Exception)

根据以下网站,您可以将exception参数传递给HttpResponseMessage.CreateErrorResponse方法( https://msdn.microsoft.com/en-us/library/jj127064(v=vs.118).aspx ) 我的问题是如何从CreateErrorResponse方法创建的HttpResponseMessage中检索exception信息。 如果无法获取exception信息,那么将exception作为输入进行方法重载的重点是什么? 澄清我不想要的答案……我知道我可以在身体内容中传递一个自定义的错误原因( http://weblogs.asp.net/fredriknormen/asp-net-web-api-exception处理 )但我真的很好奇如何使用HttpRequestMessageExtensions.CreateErrorResponse方法(HttpRequestMessage,HttpStatusCode, Exception )方法重载。 示例WebAPI控制器: Route(“location/{locationName}/Databases/{databasename}/ProcedureSession”)][LocationSetUp] public HttpResponseMessage Post([FromBody] ProcedureSessionData procedureSession) { try { throw new Exception(“test Exception”); } catch (Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } 如何在此代码中选择exception: using (var client = new HttpClient()) { client.BaseAddress = new Uri(“http://localhost/”); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”)); string api = “testApi/location/here/databases/testDb/ProcedureSession”; HttpResponseMessage response […]

如何在MVC Web API post方法中将ModelState错误返回给Kendo网格?

我无法找到一个Kendo + MVC Web API的示例,其中post / update方法返回validation错误。 看起来没有Kendo扩展可以使以下代码工作。 public HttpResponseMessage Post([ModelBinder(typeof(Prototype.WebApi.ModelBinders.DataSourceRequestModelBinder))][DataSourceRequest] DataSourceRequest request, User user) { if (this.ModelState.IsValid) { //save } return Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState.ToDataSourceResult()); } 因此,在此上下文中的ModelState是System.Web.Http.ModelBinding.ModelStateDictionary和Kendo扩展期望System.Web.Mvc.ModelStateDictionary。 那么将ModelState错误从Web API返回到Kendo的最佳方法是什么?