Tag: asp.net web api

IoC:Castle Windsor和WebAPI

我有一个使用Castle Windsor的MVC4站点,我想添加一些WebAPI调用,所以我开始在互联网上挖掘一下。 现在我不知道IoC的来龙去脉; 我按照教程了解了如何在我的项目中设置Castle Windsor,将IUnitOfWorkFactory和IApplicationService作为基本控制器中的公共属性注入,并在控制器构造函数中根据需要注入一些其他接口。 它游泳,所以我从来没有做过更多。 我正在WebAPI上阅读的所有地方,我都被告知DI使用Castle Windsor不能很好地工作,谈论IDependencyResolver和IDependencyScope 。 有几种解决方法和实现如何解决这个问题,但我不清楚的是究竟是什么问题。 包含代码片段,但假设您知道它们属于哪个类,以及如何调用它们,遗憾的是我没有。 另外,我在网上看到的所有例子都提到了一个独家的WebAPI项目,而不是一个明智地投入了几个ApiController的MVC4项目。我不知道这是怎样的,或者是否会影响到任何东西。 为什么我的标准控制器无法使用API​​控制器? 为了让WebAPI调用和标准Web调用在同一个应用程序中工作,需要做什么样的代码杂技?

可以在Asp.Net Web Api路由中使用句点吗?

我正在努力从原始的http处理程序移动API项目,我在路径中使用句点: http://server/collection/id.format 我想在Web Api(自托管)版本中遵循相同的URL架构,并尝试这样做: var c = new HttpSelfHostConfiguration(b); c.Routes.MapHttpRoute( name: “DefaultApiRoute”, routeTemplate: “{controller}/{id}.{format}”, defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional }, constraints: null ); 不幸的是,这似乎没有解决(在/ foo,/ foo / bar和/foo/bar.txt上一致的404’)。 在’format’之前使用斜杠的类似模式工作正常: var c = new HttpSelfHostConfiguration(b); c.Routes.MapHttpRoute( name: “DefaultApiRoute”, routeTemplate: “{controller}/{id}/{format}”, defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional }, constraints: null […]

如何使用客户端证书在Web API中进行身份validation和授权

我正在尝试使用客户端证书来使用Web API对设备进行身份validation和授权,并开发了一个简单的概念certificate来解决潜在解决方案的问题。 我遇到的问题是Web应用程序没有收到客户端证书。 一些人报告了这个问题, 包括在本问答中 ,但他们都没有答案。 我希望提供更多细节来重振这个问题,并希望得到我的问题的答案。 我对其他解决方案持开放态度。 主要要求是用C#编写的独立进程可以调用Web API并使用客户端证书进行身份validation。 此POC中的Web API非常简单,只返回单个值。 它使用一个属性来validation是否使用了HTTPS以及是否存在客户端证书。 public class SecureController : ApiController { [RequireHttps] public string Get(int id) { return “value”; } } 以下是RequireHttpsAttribute的代码: public class RequireHttpsAttribute : AuthorizationFilterAttribute { public override void OnAuthorization(HttpActionContext actionContext) { if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps) { actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { ReasonPhrase = “HTTPS […]

ASP.NET Web API中的可选查询字符串参数

我需要实现以下WebAPI方法: /api/books?author=XXX&title=XXX&isbn=XXX&somethingelse=XXX&date=XXX 所有查询字符串参数都可以为null。 也就是说,调用者可以指定从0到所有5个参数。 在MVC4 beta中我曾经做过以下事情: public class BooksController : ApiController { // GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01 public string GetFindBooks(string author, string title, string isbn, string somethingelse, DateTime? date) { // … } } MVC4 RC不再像这样了。 如果我指定少于5个参数,它会回复404说: 未在与请求匹配的控制器“Books”上找到任何操作。 什么是正确的方法签名,使其行为像以前一样,而不必在URL路由中指定可选参数?

在方法签名中使用async关键字在Web Api端点中返回Task

如果我想通过返回一个Task对象来编写一个非阻塞的web api动作,我可以使用或不使用async关键字这样做: 使用异步 public async Task Get() { Func slowCall = () => { Thread.Sleep(2000); return Request.CreateResponse(HttpStatusCode.OK, “Hello world”); }; var task = Task.Factory.StartNew(slowCall); return await task; } 不使用异步 public Task Get() { Func slowCall = () => { Thread.Sleep(2000); return Request.CreateResponse(HttpStatusCode.OK, “Hello world”); }; var task = Task.Factory.StartNew(slowCall); return task; } 他们都正常工作。 但是,我在编写返回Task的web api操作时看到的每个例子(在线和书籍)都使用async关键字。 […]

WebApi.Owin中的SuppressDefaultHostAuthentication还禁止webapi之外的身份validation

我遇到了一个解决方案的问题,我使用Visual Studio SPA模板中的部件在WebApi中使用Oauth身份validation使用Account Controller。 app.UseOAuthBearerTokens(OAuthOptions); 然后我在owin webapi注册中正在做 config.SuppressDefaultHostAuthentication(); 但这也会阻止webapi环境之外的默认cookie身份validation。 这是意图吗? 如果是这样,我如何设置WebApi来抑制cookie身份validation,但它仍然在其他请求的环境中活动?

如何获取已读取的内容

我有一个inheritance自ApiController的类。 它有一个像这样的Put方法: [PUT(“user/{UserId}”)] public HttpResponseMessage Put(string userId, PaymentRequest paymentRequest) { // Calling business logic and so forth here // Return proper HttpResponseMessage here } 该方法在上面工作正常。 现在我需要validation方法调用的签名,但在这里我遇到了一个问题。 签名本质上是方法+ url + body的组合。 我可以通过调用Request.Method和我可以通过调用Request.RequestUri.ToString()来获取的方法来获取该方法,但是我无法获取正文,因为它在被自动反序列化为PaymentRequest对象之前由asp.net MVC4框架。 我的第一次尝试:因为我现在已经理解了Request.Content.ReadAsStringAsync()。结果什么也没有返回。 这是因为内容只能读取一次。 我的第二次尝试:我尝试将其序列化为JSON字符串。 var serializer = new JavaScriptSerializer(); var paymentRequestAsJson = serializer.Serialize(paymentRequest); 这个问题是格式化与签名的正文部分略有不同。 它具有相同的数据,但有一些空格。 我无法改变Put-method的调用者所做的事情,因为这是第三方组件。 我该怎么办?

使用MVC Web API发布对象数组

我有一个基本的post操作,适用于RecordIem的单个对象。 我想做的是做同样的操作,但是通过使用相同的格式发布一系列请求来批量操作。 例如: public HttpResponseMessage Post(RecordItem request) { var recordItems = _recorder.RecordItem(request); return Request.CreateResponse(HttpStatusCode.OK, recordItems); } 当我发布Json时: { Id : “7UP24fVkGOxSjrcclghe_mP2-po”, System : 1, Environment : “Production” } 一切正常。 我想发布Json类似于: { Id : “7UP24fVkGOxSjrcclghe_mP2-po”, System : 1, Environment : “Production” }, { Id : “ClPE188H4TeD2LbQPeV_EzCsKVM”, System : 1, Environment : “Production”, Label : “RestTest1” }, […]

使用ASP.NET Web API进行error handling的最佳实践

您能否澄清一下Web API错误管理的最佳实践? 实际上,我不知道将try catch用于我的Api请求是否是一个好习惯。 public Vb.Order PostOrderItem(Vb.Order order) { if (OAuth.isValid(Request.Headers.GetValues(“Token”).Single()) != true) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized); throw new HttpResponseException(httpResponseMessage); } if (!ModelState.IsValid) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); throw new HttpResponseException(httpResponseMessage); } try { return Vb.Document.Generate(order); } catch (Exception ex) { logger.Error(ex); HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); httpResponseMessage.Content = new StringContent(ex.Message); throw […]

Web API OData Inlinecount无法正常工作

我在ASP.NET Web API应用程序中使用开箱即用的ValuesController public class ValuesController : ApiController { // GET api/values [Queryable(PageSize = 1)] public IQueryable Get() { return new string[] { “value1”, “value2”, “value3”, “value4”, “value5” }.AsQueryable(); } } 当我get http://localhost/api/values?$inlinecount=allpages 这是回应 value1 我没有注释config.EnableQuerySupport(); 过滤,排序工作正常。 如果我尝试get http://localhost/api/values?$inlinecount=XXXXX我得到一个exception,所以似乎Web API应用程序知道inlinecount The query specified in the URI is not valid. ‘xxx’ is not a valid value […]